63 lines
1.6 KiB
C++
63 lines
1.6 KiB
C++
#include "Game.hpp"
|
|
|
|
#include <chrono>
|
|
|
|
Game::Game()
|
|
: pacMan(board),
|
|
pellets(board),
|
|
superPellets(board) {}
|
|
|
|
auto Game::now() {
|
|
return std::chrono::system_clock::now();
|
|
}
|
|
|
|
void Game::run() {
|
|
|
|
const std::chrono::milliseconds delta_time (1000/60);
|
|
|
|
std::chrono::milliseconds t(0);
|
|
std::chrono::milliseconds accumulator(0);
|
|
auto current_time = now();
|
|
|
|
InputState inputState;
|
|
|
|
while (true) {
|
|
auto newTime = now();
|
|
auto frameTime = std::chrono::duration_cast<std::chrono::milliseconds>(newTime - current_time);
|
|
current_time = newTime;
|
|
accumulator += frameTime;
|
|
processEvents(inputState);
|
|
if(inputState.close)
|
|
return;
|
|
while ( accumulator >= delta_time ) {
|
|
pacMan.update(delta_time, inputState, board);
|
|
eatPellets();
|
|
accumulator -= delta_time;
|
|
t += delta_time;
|
|
}
|
|
canvas.update(pacMan, pellets, superPellets);
|
|
}
|
|
}
|
|
|
|
void Game::eatPellets() {
|
|
const auto pos = pacMan.positionInGrid();
|
|
pellets.eatPelletAtPosition(pos);
|
|
superPellets.eatPelletAtPosition(pos);
|
|
}
|
|
|
|
void Game::processEvents(InputState & inputState) {
|
|
|
|
auto event = canvas.pollEvent();
|
|
if (event && event->type == sf::Event::Closed) {
|
|
inputState.close = true;
|
|
return;
|
|
}
|
|
|
|
inputState.down = inputState.up = inputState.left = inputState.right = false;
|
|
|
|
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);
|
|
}
|