-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
104 lines (91 loc) · 2.4 KB
/
Copy pathgame.js
File metadata and controls
104 lines (91 loc) · 2.4 KB
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
const websocket = require("ws");
const game = function(gameID) {
this.playerA = null;
this.playerB = null;
this.id = gameID;
this.turn = null;
this.gameState = "0 JOINT";
};
game.prototype.transitionStates = {
"0 JOINT": 0,
"1 JOINT": 1,
"2 JOINT": 2,
"TURN": 3,
"A": 4, //A won
"B": 5, //B won
"ABORTED": 6,
"TIED" : 7
};
game.prototype.transitionMatrix = [
[0, 1, 0, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 1],
[0, 0, 0, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]
];
game.prototype.isValidTransition = function(from, to) {
let i, j;
if (!(from in game.prototype.transitionStates)) {
return false;
} else {
i = game.prototype.transitionStates[from];
}
if (!(to in game.prototype.transitionStates)) {
return false;
} else {
j = game.prototype.transitionStates[to];
}
return game.prototype.transitionMatrix[i][j] > 0;
};
game.prototype.isValidState = function(s) {
return s in game.prototype.transitionStates;
};
game.prototype.setStatus = function(w) {
if (
game.prototype.isValidState(w) &&
game.prototype.isValidTransition(this.gameState, w)
) {
this.gameState = w;
console.log("[STATUS] %s", this.gameState);
} else {
return new Error(
`Impossible status change from ${this.gameState} to ${w}`
);
}
};
game.prototype.setPlayerTurn = function(w) {
if (this.gameState != "1 JOINT" && this.gameState != "2 JOINT") {
return new Error(
`Trying to set player turn, but game status is ${this.gameState}`
);
}
this.turn = w;
};
game.prototype.getTurn = function() {
return this.turn;
};
game.prototype.hasTwoConnectedPlayers = function() {
return this.gameState == "2 JOINT";
};
game.prototype.addPlayer = function(p) {
if (this.gameState != "0 JOINT" && this.gameState != "1 JOINT") {
return new Error(
`Invalid call to addPlayer, current state is ${this.gameState}`
);
}
const error = this.setStatus("1 JOINT");
if (error instanceof Error) {
this.setStatus("2 JOINT");
}
if (this.playerA == null) {
this.playerA = p;
return "A";
} else {
this.playerB = p;
return "B";
}
};
module.exports = game;