-
Notifications
You must be signed in to change notification settings - Fork 3
/
game.js
111 lines (96 loc) · 2.35 KB
/
game.js
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
var STARTING_TROOPS = 60;
var STARTING_TERRITORIES = 4;
var TURN_LENGTH = 5;
var Territory = require('./territory');
var Player = require('./player');
var territoriesInPlay = require('./public/java/lib/0_countriesdata');
var territories = [];
for (var i in territoriesInPlay) {
var name = territoriesInPlay[i]
var t = new Territory(name);
territories.push(t);
}
function addNewPlayer() {
newPlayer = new Player();
initTroops(newPlayer);
return newPlayer;
}
function initTroops(player) {
var terrs = emptyTerritories(STARTING_TERRITORIES);
for (var i in terrs) {
terrs[i].troops[player.id] = Math.floor(STARTING_TROOPS/STARTING_TERRITORIES);
}
}
// if x is undefined, returns all empty territories
function emptyTerritories(x) {
x = x || territories.length;
var terrs = [];
var i = 0;
while ( i < territories.length && x > 0) {
if ( territories[i].isEmpty() ) {
terrs.push(territories[i]);
x--;
}
i++;
}
return terrs;
}
function moveTroops(player, from, to, num) {
var i = territories.length;
// grabbing territory objects from names
while (i--) {
if (territories[i].name == from) {
from = territories[i];
};
if (territories[i].name == to) {
to = territories[i];
};
}
// moving the troops
if ( from.remTroops(player.id, num) ) {
to.addTroops(player.id, num)
}
};
function evaluateState() {
var results = ['A new turn begins.'];
var i = territories.length;
while (i--) {
var terr = territories[i];
terr.lastOneStanding(terr.troops);
}
return results;
}
function removePlayer(player) {
var i = territories.length;
while (i--) {
territories[i].removePlayer(player.id);
}
}
function armies(player) {
var results = {};
var i = territories.length;
while (i--) {
if (territories[i].contains(player.id)) {
var country = territories[i].name;
var num = territories[i].troops[player.id];
results[country] = num;
}
}
return results;
}
// summarises all game info
function state() {
var _state = {};
_state.territories = territories;
_state.turnLength = TURN_LENGTH;
return _state;
}
module.exports = {
removePlayer : removePlayer,
addNewPlayer : addNewPlayer,
evaluateState : evaluateState,
state : state,
moveTroops : moveTroops,
armies : armies,
turnLength : TURN_LENGTH
}