aboutsummaryrefslogtreecommitdiff
path: root/src/openvic/GameAdvancementHook.cpp
blob: 0fcdd03074529a96f32a3bb207a317c0d9f12a09 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "GameAdvancementHook.hpp"

using namespace OpenVic;

const std::vector<std::chrono::milliseconds> 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<std::chrono::high_resolution_clock> currentTime = std::chrono::high_resolution_clock::now();
      if (std::chrono::duration_cast<std::chrono::milliseconds>(currentTime - lastPolledTime) >= GAME_SPEEDS[currentSpeed]) {
         lastPolledTime = currentTime;
         if (triggerFunction) triggerFunction();
      }
   }
   if (refreshFunction) refreshFunction();
}

void GameAdvancementHook::reset() {
   isPaused = true;
   currentSpeed = 0;
}