holesome/src/game/game.cpp

97 lines
1.9 KiB
C++
Raw Normal View History

2023-04-26 22:48:15 +02:00
#include <utility>
2023-04-27 23:05:19 +02:00
#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
2023-04-26 22:48:15 +02:00
#include "game.h"
Game::Game(std::shared_ptr<sf::RenderWindow> window) : window(std::move(window)),
2023-05-10 11:03:14 +02:00
gameObjects()
{
2023-04-26 22:48:15 +02:00
}
Game::~Game()
{
for (auto &gameObject: gameObjects)
{
delete gameObject;
}
}
void Game::run()
{
sf::Clock clock;
sf::Time TimeSinceLastUpdate = sf::seconds(0);
2023-04-26 22:48:15 +02:00
while (window->isOpen())
{
InputMapper::getInstance()->processEvents();
TimeSinceLastUpdate += clock.restart();
while (TimeSinceLastUpdate >= FRAME_TIME)
{
TimeSinceLastUpdate -= FRAME_TIME;
2023-04-27 23:05:19 +02:00
update();
InputMapper::getInstance()->processEvents();
2023-04-27 23:05:19 +02:00
}
drawFrame();
2023-04-26 22:48:15 +02:00
}
}
void Game::exit()
{
window->close();
2023-04-27 23:05:19 +02:00
}
void Game::drawFrame()
{
window->clear(sf::Color::Black);
for (auto &gameObject: gameObjects)
{
gameObject->draw(window.get());
2023-04-27 23:05:19 +02:00
}
window->display();
2023-04-27 23:05:19 +02:00
}
void Game::addGameObject(GameObject *gameObject)
{
gameObjects.push_back(gameObject);
}
2023-05-03 01:33:14 +02:00
void Game::update()
{
// Basic Updates
for (auto &gameObject: gameObjects)
{
2023-05-10 11:03:14 +02:00
gameObject->update(this);
}
// Late updates
for (auto &gameObject: gameObjects)
{
gameObject->lateUpdate(this);
}
}
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;
}