pacman/lib/Game.cpp

54 lines
1.4 KiB
C++
Raw Normal View History

#include "Game.hpp"
2021-07-08 14:57:18 +00:00
#include "GameState.hpp"
2020-11-27 13:10:09 +00:00
#include <chrono>
2021-07-05 12:10:01 +00:00
namespace pacman {
2020-11-27 13:10:09 +00:00
void Game::run() {
2021-06-24 11:32:52 +00:00
const std::chrono::milliseconds delta_time(1000 / 60);
std::chrono::milliseconds accumulator(0);
2021-07-08 16:12:03 +00:00
auto current_time = std::chrono::system_clock::now();
2021-06-24 11:32:52 +00:00
while (true) {
const auto newTime = std::chrono::system_clock::now();
const auto frameTime = std::chrono::duration_cast<std::chrono::milliseconds>(newTime - current_time);
2021-06-24 11:32:52 +00:00
current_time = newTime;
accumulator += frameTime;
processEvents(gameState.inputState);
if (gameState.inputState.close)
2021-06-24 11:32:52 +00:00
return;
2021-06-24 11:32:52 +00:00
while (accumulator >= delta_time) {
gameState.step(delta_time);
2021-06-24 11:32:52 +00:00
accumulator -= delta_time;
}
2021-07-15 07:14:25 +00:00
2021-10-06 11:30:07 +00:00
canvas.render(gameState);
2021-06-24 08:32:54 +00:00
}
2021-06-16 11:59:16 +00:00
}
2020-11-27 13:10:09 +00:00
void Game::processEvents(InputState & inputState) {
const auto event = canvas.pollEvent();
2021-07-06 15:09:42 +00:00
if (event && event.value().type == sf::Event::Closed) {
inputState.close = true;
return;
2020-11-27 13:10:09 +00:00
}
2021-10-05 12:48:26 +00:00
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
inputState.enableAI = !inputState.enableAI;
}
2021-10-18 11:25:25 +00:00
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Q)) {
exit(0);
}
inputState.down = sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Down);
inputState.up = sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Up);
inputState.left = sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Left);
inputState.right = sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Right);
2020-11-27 13:10:09 +00:00
}
2021-07-05 12:10:01 +00:00
} // namespace pacman