This repository has been archived by the owner on Oct 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInstance.js
88 lines (75 loc) · 2.44 KB
/
Instance.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
const exec = require('child_process');
const EventEmitter = require('events');
class Instance {
constructor(api, instanceID, manager, enginePath) {
this.api = api;
this.instanceID = instanceID;
this.manager = manager;
this.enginePath = enginePath;
this.updateState('Init');
}
start() {
this.api.beginGameStream(this.instanceID, (res) => this.gameStream(res));
}
gameStream(res) {
let instance = this;
res.on('data', function (chunk) {
let data;
try {
data = JSON.parse(String(chunk))
} catch (error) { return };
instance.handleEvent(data);
});
res.on('end', function (msg) {
});
}
handleEvent(event) {
switch (event.type) {
case 'gameFull':
this.setInstanceColor(event.white.id == this.api.botID);
this.handleMove(event.clock.initial, event.state.moves);
break;
case 'gameState':
this.handleMove(event.btime, event.moves);
break;
}
}
handleMove(time, moves) {
if (!this.isInstanceColor(moves)) {
this.updateState('Waiting for Opponent');
return;
}
this.generateMove(this, time, moves, this.playMove)
}
generateMove(instance, time, moves, callback) {
this.updateState('Generating Move');
exec.exec(this.enginePath + " \"" + time + "\"" + " \"" + moves + "\"", (err, stdout) => {
callback(instance, err, stdout);
});
}
playMove(instance, err, stdout) {
instance.updateState('Sending Move');
if (err != null) {
console.log("engine error ", err);
}
let segmentedData = stdout.split('\n');
if (stdout.includes('draw'))
instance.api.sendDrawRequest(instance.instanceID);
else
instance.api.sendMove(instance.instanceID, segmentedData[0]);
}
setInstanceColor(isWhite) {
if (isWhite)
this.instanceColor = 'white';
else
this.instanceColor = 'black';
}
isInstanceColor(moves) {
return (this.instanceColor == ((1 - (moves.length == 0) - moves.split(' ').length % 2) ? "white" : "black"));
}
updateState(state) {
this.state = state;
this.manager.emit('instanceStateUpdate');
}
}
module.exports = Instance;