A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Game.h 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #pragma once
  2. #include <bitset>
  3. #include <map>
  4. #include <string>
  5. #include <optional>
  6. #include <SDL.h>
  7. #include <cygnet/Renderer.h>
  8. #include <cygnet/util.h>
  9. #include "common.h"
  10. #include "Mod.h"
  11. #include "World.h"
  12. namespace Swan {
  13. class Game {
  14. public:
  15. void createWorld(const std::string &worldgen, const std::vector<std::string> &modPaths);
  16. void onKeyDown(SDL_Keysym sym) {
  17. pressedKeys_[sym.scancode] = true;
  18. didPressKeys_[sym.scancode] = true;
  19. }
  20. void onKeyUp(SDL_Keysym sym) {
  21. pressedKeys_[sym.scancode] = false;
  22. didReleaseKeys_[sym.scancode] = true;
  23. }
  24. void onMouseMove(Sint32 x, Sint32 y) {
  25. mousePos_ = (Vec2{(float)x, (float)y} / (Vec2)cam_.size) * renderer_.winScale();
  26. }
  27. void onMouseDown(Sint32 x, Sint32 y, Uint8 button) {
  28. onMouseMove(x, y);
  29. pressedButtons_[button] = true;
  30. didPressButtons_[button] = true;
  31. }
  32. void onMouseUp(Sint32 x, Sint32 y, Uint8 button) {
  33. onMouseMove(x, y);
  34. pressedButtons_[button] = false;
  35. didReleaseButtons_[button] = true;
  36. }
  37. void onScrollWheel(Sint32 y) {
  38. didScroll_ = (y > 0 ? 1 : -1 );
  39. }
  40. bool isKeyPressed(SDL_Scancode code) { return pressedKeys_[code]; }
  41. bool wasKeyPressed(SDL_Scancode code) { return didPressKeys_[code]; }
  42. bool wasKeyReleased(SDL_Scancode code) { return didReleaseKeys_[code]; }
  43. Vec2 getMousePos() { return mousePos_; }
  44. bool isMousePressed(Uint8 button) { return pressedButtons_[button]; }
  45. bool wasMousePressed(Uint8 button) { return didPressButtons_[button]; }
  46. bool wasMouseReleased(Uint8 button) { return didReleaseButtons_[button]; }
  47. int wasWheelScrolled() { return didScroll_; }
  48. TilePos getMouseTile();
  49. Cygnet::Color backgroundColor();
  50. void draw();
  51. void update(float dt);
  52. void tick(float dt);
  53. std::unique_ptr<World> world_ = NULL;
  54. Cygnet::Renderer renderer_;
  55. Cygnet::RenderCamera cam_{.zoom = 0.125};
  56. private:
  57. std::bitset<SDL_NUM_SCANCODES> pressedKeys_;
  58. std::bitset<SDL_NUM_SCANCODES> didPressKeys_;
  59. std::bitset<SDL_NUM_SCANCODES> didReleaseKeys_;
  60. Vec2 mousePos_;
  61. std::bitset<SDL_BUTTON_X2> pressedButtons_;
  62. std::bitset<SDL_BUTTON_X2> didPressButtons_;
  63. std::bitset<SDL_BUTTON_X2> didReleaseButtons_;
  64. int didScroll_ = 0;
  65. };
  66. }