GameCore.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. //
  2. // Created by jovian on 18/07/17.
  3. //
  4. // Basics
  5. #include <iostream>
  6. #include "GameCore.h"
  7. #include "Graphics/MetaField.h"
  8. GameCore::GameCore()
  9. : m_input(nullptr), m_rend(nullptr) {}
  10. GameCore::~GameCore() {
  11. // Input
  12. if (m_input != nullptr) {
  13. delete m_input;
  14. m_input = nullptr;
  15. }
  16. // Destroy SDL renderer
  17. if (m_rend != nullptr) {
  18. delete m_rend;
  19. m_rend = nullptr;
  20. }
  21. }
  22. bool GameCore::initialize() {
  23. // Already initialized
  24. if (m_input != nullptr)
  25. return false;
  26. // Error check
  27. bool okay(true);
  28. // Create display
  29. m_rend = new Renderer;
  30. okay = okay && m_rend->initialize();
  31. // Create hardware interface
  32. m_input = new Input;
  33. m_input->setWindow(m_rend->getWindow());
  34. // End
  35. return okay;
  36. }
  37. void GameCore::start() {
  38. // Time
  39. Uint32 frameRate(60); // Frame per second
  40. Uint32 prevTime(0); // Previous chrono
  41. Uint32 waitTime(1000 / frameRate); // Time to wait between each frame
  42. Uint32 osBuffer(4); // To prevent SDL_Delay mistake : high > less mistake, more CPU usage
  43. // Matrix field
  44. bool field[WIN_H][WIN_W];
  45. MetaField meta;
  46. std::vector<MetaBall> balls;
  47. // Main loop
  48. while (!m_input->isFinished() && !m_input->getKey(SDL_SCANCODE_ESCAPE)) {
  49. // Update events
  50. m_input->updateEvents();
  51. // Rendering
  52. m_rend->clearWindow();
  53. meta.clean();
  54. if (m_input->getInstantKey(SDL_SCANCODE_E))
  55. balls.push_back({m_input->getX(), m_input->getY(), 1000.0});
  56. for (auto b : balls)
  57. meta.disturb(b.y, b.x, b.power);
  58. meta.disturb(m_input->getY(), m_input->getX(), 1000.0);
  59. meta.binary(field, 1.0);
  60. m_rend->renderBoolMatrix(field);
  61. m_rend->presentWindow();
  62. // todo Remove debug
  63. /*Uint32 debug_conso(SDL_GetTicks() - prevTime);
  64. std::cout << "Time use : " << debug_conso << std::endl;*/
  65. // Pause
  66. if (SDL_GetTicks() + osBuffer < prevTime + waitTime)
  67. SDL_Delay(waitTime + prevTime - SDL_GetTicks() - osBuffer);
  68. while (SDL_GetTicks() < prevTime + waitTime) {}
  69. prevTime = SDL_GetTicks();
  70. }
  71. }