From c92481448159d3a363d6a99b3025bd2358c3dab6 Mon Sep 17 00:00:00 2001 From: ClarkeCode Date: Sun, 30 Apr 2023 20:48:35 -0400 Subject: Initial commit --- GameAdvancementHook.cpp | 72 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 GameAdvancementHook.cpp (limited to 'GameAdvancementHook.cpp') diff --git a/GameAdvancementHook.cpp b/GameAdvancementHook.cpp new file mode 100644 index 0000000..d90b7b1 --- /dev/null +++ b/GameAdvancementHook.cpp @@ -0,0 +1,72 @@ +#include "GameAdvancementHook.hpp" + +using namespace OpenVic2; + +const std::vector GameAdvancementHook::GAME_SPEEDS = { + std::chrono::milliseconds{ 4000 }, + std::chrono::milliseconds{ 3000 }, + std::chrono::milliseconds{ 2000 }, + std::chrono::milliseconds{ 1000 }, + std::chrono::milliseconds{ 100 }, + std::chrono::milliseconds{ 1 } }; + +GameAdvancementHook::GameAdvancementHook(AdvancementFunction tickFunction, RefreshFunction updateFunction, bool startPaused, speed_t startingSpeed) + : triggerFunction{ tickFunction }, refreshFunction{ updateFunction }, isPaused{ startPaused } { + lastPolledTime = std::chrono::high_resolution_clock::now(); + setSimulationSpeed(startingSpeed); +} + +void GameAdvancementHook::setSimulationSpeed(speed_t speed) { + if (speed < 0) + currentSpeed = 0; + else if (speed >= GAME_SPEEDS.size()) + currentSpeed = GAME_SPEEDS.size() - 1; + else + currentSpeed = speed; +} + +GameAdvancementHook::speed_t GameAdvancementHook::getSimulationSpeed() const { + return currentSpeed; +} + +void GameAdvancementHook::increaseSimulationSpeed() { + setSimulationSpeed(currentSpeed + 1); +} + +void GameAdvancementHook::decreaseSimulationSpeed() { + setSimulationSpeed(currentSpeed - 1); +} + +bool GameAdvancementHook::canIncreaseSimulationSpeed() const { + return currentSpeed + 1 < GAME_SPEEDS.size(); +} + +bool GameAdvancementHook::canDecreaseSimulationSpeed() const { + return currentSpeed > 0; +} + +GameAdvancementHook& GameAdvancementHook::operator++() { + increaseSimulationSpeed(); + return *this; +}; + +GameAdvancementHook& GameAdvancementHook::operator--() { + decreaseSimulationSpeed(); + return *this; +}; + +void GameAdvancementHook::conditionallyAdvanceGame() { + if (!isPaused) { + std::chrono::time_point currentTime = std::chrono::high_resolution_clock::now(); + if (std::chrono::duration_cast(currentTime - lastPolledTime) >= GAME_SPEEDS[currentSpeed]) { + lastPolledTime = currentTime; + if (triggerFunction) triggerFunction(); + } + } + if (refreshFunction) refreshFunction(); +} + +void GameAdvancementHook::reset() { + isPaused = true; + currentSpeed = 0; +} -- cgit v1.2.3-56-ga3b1