-
Notifications
You must be signed in to change notification settings - Fork 0
/
power.cpp
74 lines (63 loc) · 1.82 KB
/
power.cpp
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
73
74
#include "power.hpp"
namespace TerraNova {
void PowerGrid::StartTurn() {
producers.StartTurn();
consumers.StartTurn();
BalancePower();
}
void PowerGrid::EndTurn() {
producers.EndTurn();
consumers.EndTurn();
}
// Determine if the given building is a producer or consumer of power and add it
// to the appropriate list. It should not be possible for any single building to
// be both.
void PowerGrid::AddBuilding(std::shared_ptr<Building> newBuilding) {
if (!newBuilding) {
std::cerr << "Warning: tried to add a null building to a power grid."
<< std::endl;
return;
}
if (newBuilding->PowerProduction() > 0) {
producers.push_back(newBuilding);
newBuilding->PowerOn();
} else {
if (newBuilding->PowerConsumption() > 0) {
consumers.push_back(newBuilding);
} else {
std::cerr << "Warning: tried to add a " << newBuilding->Name() <<
" to a power grid but it neither produces nor consumes power."
<< std::endl;
return;
}
}
}
void PowerGrid::AddBuilding(std::weak_ptr<Building> newBuilding) {
AddBuilding(newBuilding.lock());
}
const int& PowerGrid::AvailablePower() const {
return availablePower;
}
const int& PowerGrid::MaximumPower() const {
return maximumPower;
}
// Find out how much power is being produced, then go through the list of
// consumers from earliest to latest, powering them up if possible and powering
// them down if not (then moving on to the next one in line).
void PowerGrid::BalancePower() {
maximumPower = 0;
for (const auto& producer : producers) {
maximumPower += producer->PowerProduction();
}
availablePower = maximumPower;
for (auto& consumer : consumers) {
int powerDraw = consumer->PowerConsumption();
if (powerDraw <= availablePower) {
consumer->PowerOn();
availablePower -= powerDraw;
} else {
consumer->PowerOff();
}
}
}
} // namespace TerraNova