-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgames.js
executable file
·133 lines (105 loc) · 2.69 KB
/
games.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
/// Handles the state of the board and processes messages from the clients that are playing the game.
///
/// This class checks the validity of the moves played and delivers the (private) messages
/// to the players.
const process = require("process");
let child_process = require('child_process');
const readline = require('readline');
class Game {
constructor() {
//
}
makeMove(moveStr) {
//...
}
reset() {
//
}
getFen() {
//
}
}
class ChessCLIGame extends Game {
constructor(config) {
super();
this._events = {
"game.answer": []
};
this.child = child_process.exec(config["backend_command"], {
cwd: config["backend_cwd"],
encoding: "utf8"
}, (error, stdout, stderr) => {
//nothing to do
});
this.rl = readline.createInterface({
input: this.child.stdout,
output: this.child.stdin
});
this.child.stderr.on('data', data => {
console.log(`game script reported an error: ${data}`);
});
this.child.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
}
_sendMessage(msg) {
this.rl.question(msg, (answer) => {
this.doEvent("game.answer", answer);
});
}
makeMove(moveStr) {
//only single lines are accepted
if (moveStr.indexOf("\n") != -1) {
process.nextTick(() => {
this.doEvent("game.answer", "rejected");
});
}
//filter command strings
if ((moveStr == "new") || (moveStr == "close") || (moveStr == "fen") || (moveStr == "fen a") || (moveStr == "fen b")) {
process.nextTick(() => {
this.doEvent("game.answer", "rejected");
});
}
this._sendMessage(moveStr+"\n");
}
reset() {
this._sendMessage("new\n");
}
getFen(board) {
if (board == "") {
this._sendMessage("fen\n");
return;
}
if ((board == "a") || (board == "b")) {
this._sendMessage("fen "+board+"\n");
} else {
throw new Error("invalid board name: "+board);
}
}
getBpgn(data) {
this._sendMessage("bpgn "+JSON.stringify(data)+"\n");
}
close() {
this._sendMessage("close\n");
}
on(eventName, eventHandler) {
let handlers = this._events[eventName];
if (handlers === undefined) {
throw new Error("unknown event name: " + eventName);
}
handlers.push(eventHandler);
}
doEvent(eventName, data) {
let handlers = this._events[eventName];
if (handlers === undefined) {
throw new Error("unknown event name:" + eventName);
}
for (let handler of handlers) {
handler(data);
}
}
}
module.exports = {
Game: Game,
ChessCLIGame: ChessCLIGame
};