holesome/src/game/game.cpp

115 lines
2.2 KiB
C++

#include <utility>
#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include "game.h"
Game::Game(std::shared_ptr<sf::RenderWindow> window) : window(std::move(window)),
gameObjects(),
views()
{
}
Game::~Game()
{
for (auto &gameObject: gameObjects)
{
delete gameObject;
}
}
void Game::run()
{
sf::Clock clock;
sf::Time TimeSinceLastUpdate = sf::seconds(0);
while (window->isOpen())
{
InputMapper::getInstance()->processEvents();
TimeSinceLastUpdate += clock.restart();
while (TimeSinceLastUpdate >= FRAME_TIME)
{
TimeSinceLastUpdate -= FRAME_TIME;
update();
InputMapper::getInstance()->processEvents();
}
drawFrame();
}
}
void Game::exit()
{
window->close();
}
void Game::drawFrame()
{
window->clear(sf::Color::Black);
for (auto &gameObject: gameObjects)
{
if (gameObject->getActive())
{
gameObject->draw(window.get());
}
}
window->display();
}
void Game::addGameObject(GameObject *gameObject)
{
gameObjects.push_back(gameObject);
}
void Game::update()
{
// Basic Updates
for (auto &gameObject: gameObjects)
{
if (gameObject->getActive())
{
gameObject->update();
}
}
// Late updates
for (auto &gameObject: gameObjects)
{
if (gameObject->getActive())
{
gameObject->lateUpdate();
}
}
InputMapper::getInstance()->updateIdentities();
}
std::shared_ptr<Game> Game::getInstance()
{
if (singletonInstance == nullptr)
{
throw std::runtime_error("Game instance has to be initialized first.");
}
return singletonInstance;
}
std::shared_ptr<Game> Game::constructInstance(const std::shared_ptr<sf::RenderWindow> &window)
{
if (singletonInstance != nullptr)
{
throw std::runtime_error("Game instance has already been initialized.");
}
singletonInstance = std::make_shared<Game>(window);
return singletonInstance;
}
void Game::registerView(TrackingView *view)
{
views.push_back(view);
}