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.cc 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. #include "Game.h"
  2. #include <math.h>
  3. #include <time.h>
  4. #include <memory>
  5. #include "log.h"
  6. #include "Tile.h"
  7. #include "OS.h"
  8. #include "Win.h"
  9. namespace Swan {
  10. std::optional<ModWrapper> Game::loadMod(std::string path, World &world) {
  11. OS::Dynlib dl(path + "/mod");
  12. auto create = dl.get<Mod *(*)(World &)>("mod_create");
  13. if (create == NULL) {
  14. warn << path << ": No 'mod_create' function!";
  15. return std::nullopt;
  16. }
  17. std::unique_ptr<Mod> mod(create(world));
  18. return std::make_optional<ModWrapper>(
  19. std::move(mod), std::move(path), std::move(dl));
  20. }
  21. void Game::createWorld(const std::string &worldgen, const std::vector<std::string> &modpaths) {
  22. world_.reset(new World(this, time(NULL)));
  23. for (auto &modpath: modpaths) {
  24. auto mod = loadMod(modpath, *world_);
  25. if (mod)
  26. world_->addMod(std::move(*mod));
  27. }
  28. world_->setWorldGen(worldgen);
  29. world_->setCurrentPlane(world_->addPlane());
  30. world_->spawnPlayer();
  31. }
  32. TilePos Game::getMouseTile() {
  33. auto mousePos = getMousePos();
  34. return TilePos(
  35. (int)floor(win_.cam_.x + mousePos.x / (Swan::TILE_SIZE * win_.zoom_)),
  36. (int)floor(win_.cam_.y + mousePos.y / (Swan::TILE_SIZE * win_.zoom_)));
  37. }
  38. SDL_Color Game::backgroundColor() {
  39. return world_->backgroundColor();
  40. }
  41. void Game::draw() {
  42. world_->draw(win_);
  43. }
  44. void Game::update(float dt) {
  45. world_->update(dt);
  46. // Zoom the window using the scroll wheel
  47. win_.zoom_ += (float)wasWheelScrolled() * 0.1f * win_.zoom_;
  48. if (win_.zoom_ > 3)
  49. win_.zoom_ = 3;
  50. else if (win_.zoom_ < 0.3)
  51. win_.zoom_ = 0.3;
  52. did_scroll_ = 0;
  53. did_press_keys_.reset();
  54. did_release_keys_.reset();
  55. did_press_buttons_.reset();
  56. did_release_buttons_.reset();
  57. }
  58. void Game::tick(float dt) {
  59. world_->tick(dt);
  60. }
  61. }