-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathenginegame.js
More file actions
268 lines (250 loc) · 8.75 KB
/
Copy pathenginegame.js
File metadata and controls
268 lines (250 loc) · 8.75 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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
function engineGame(options) {
options = options || {}
var game = new Chess();
var board;
var engine = new Worker(options.stockfishjs || 'stockfish.js');
var engineStatus = {};
var displayScore = false;
var time = { wtime: 300000, btime: 300000, winc: 2000, binc: 2000 };
var playerColor = 'white';
var clockTimeoutID = null;
var isEngineRunning = false;
// do not pick up pieces if the game is over
// only pick up pieces for White
var onDragStart = function(source, piece, position, orientation) {
var re = playerColor == 'white' ? /^b/ : /^w/
if (game.game_over() ||
piece.search(re) !== -1) {
return false;
}
};
function uciCmd(cmd) {
engine.postMessage(cmd);
}
uciCmd('uci');
function displayStatus() {
var status = 'Engine: ';
if(!engineStatus.engineLoaded) {
status += 'loading...';
} else if(!engineStatus.engineReady) {
status += 'loaded...';
} else {
status += 'ready.';
}
status += ' Book: ' + engineStatus.book;
if(engineStatus.search) {
status += '<br>' + engineStatus.search;
if(engineStatus.score && displayScore) {
status += ' Score: ' + engineStatus.score;
}
}
$('#engineStatus').html(status);
}
function displayClock(color, t) {
var isRunning = false;
if(time.startTime > 0 && color == time.clockColor) {
t = Math.max(0, t + time.startTime - Date.now());
isRunning = true;
}
var id = color == playerColor ? '#time2' : '#time1';
var sec = Math.ceil(t / 1000);
var min = Math.floor(sec / 60);
sec -= min * 60;
var hours = Math.floor(min / 60);
min -= hours * 60;
var display = hours + ':' + ('0' + min).slice(-2) + ':' + ('0' + sec).slice(-2);
if(isRunning) {
display += sec & 1 ? ' <--' : ' <-';
}
$(id).text(display);
}
function updateClock() {
displayClock('white', time.wtime);
displayClock('black', time.btime);
}
function clockTick() {
updateClock();
var t = (time.clockColor == 'white' ? time.wtime : time.btime) + time.startTime - Date.now();
var timeToNextSecond = (t % 1000) + 1;
clockTimeoutID = setTimeout(clockTick, timeToNextSecond);
}
function stopClock() {
if(clockTimeoutID !== null) {
clearTimeout(clockTimeoutID);
clockTimeoutID = null;
}
if(time.startTime > 0) {
var elapsed = Date.now() - time.startTime;
time.startTime = null;
if(time.clockColor == 'white') {
time.wtime = Math.max(0, time.wtime - elapsed);
} else {
time.btime = Math.max(0, time.btime - elapsed);
}
}
}
function startClock() {
if(game.turn() == 'w') {
time.wtime += time.winc;
time.clockColor = 'white';
} else {
time.btime += time.binc;
time.clockColor = 'black';
}
time.startTime = Date.now();
clockTick();
}
function prepareMove() {
stopClock();
$('#pgn').text(game.pgn());
board.position(game.fen());
updateClock();
var turn = game.turn() == 'w' ? 'white' : 'black';
if(!game.game_over()) {
if(turn != playerColor) {
var moves = '';
var history = game.history({verbose: true});
for(var i = 0; i < history.length; ++i) {
var move = history[i];
moves += ' ' + move.from + move.to + (move.promotion ? move.promotion : '');
}
uciCmd('position startpos moves' + moves);
if(time.depth) {
uciCmd('go depth ' + time.depth);
} else if(time.nodes) {
uciCmd('go nodes ' + time.nodes);
} else {
uciCmd('go wtime ' + time.wtime + ' winc ' + time.winc + ' btime ' + time.btime + ' binc ' + time.binc);
}
isEngineRunning = true;
}
if(game.history().length >= 2 && !time.depth && !time.nodes) {
startClock();
}
}
}
engine.onmessage = function(event) {
var line = event.data;
if(line == 'uciok') {
engineStatus.engineLoaded = true;
} else if(line == 'readyok') {
engineStatus.engineReady = true;
} else {
var match = line.match(/^bestmove ([a-h][1-8])([a-h][1-8])([qrbk])?/);
if(match) {
isEngineRunning = false;
game.move({from: match[1], to: match[2], promotion: match[3]});
prepareMove();
} else if(match = line.match(/^info .*\bdepth (\d+) .*\bnps (\d+)/)) {
engineStatus.search = 'Depth: ' + match[1] + ' Nps: ' + match[2];
}
if(match = line.match(/^info .*\bscore (\w+) (-?\d+)/)) {
var score = parseInt(match[2]) * (game.turn() == 'w' ? 1 : -1);
if(match[1] == 'cp') {
engineStatus.score = (score / 100.0).toFixed(2);
} else if(match[1] == 'mate') {
engineStatus.score = '#' + score;
}
if(match = line.match(/\b(upper|lower)bound\b/)) {
engineStatus.score = ((match[1] == 'upper') == (game.turn() == 'w') ? '<= ' : '>= ') + engineStatus.score
}
}
}
displayStatus();
};
var onDrop = function(source, target) {
// see if the move is legal
var move = game.move({
from: source,
to: target,
promotion: 'q' // NOTE: always promote to a pawn for example simplicity
});
// illegal move
if (move === null) return 'snapback';
prepareMove();
};
// update the board position after the piece snap
// for castling, en passant, pawn promotion
var onSnapEnd = function() {
board.position(game.fen());
};
var cfg = {
draggable: true,
position: 'start',
onDragStart: onDragStart,
onDrop: onDrop,
onSnapEnd: onSnapEnd
};
if(options.book) {
var bookRequest = new XMLHttpRequest();
bookRequest.open('GET', options.book, true);
bookRequest.responseType = "arraybuffer";
bookRequest.onload = function(event) {
if(bookRequest.status == 200) {
engine.postMessage({book: bookRequest.response});
engineStatus.book = 'ready.';
displayStatus();
} else {
engineStatus.book = 'failed!';
displayStatus();
}
};
bookRequest.send(null);
} else {
engineStatus.book = 'none';
}
board = new ChessBoard('board', cfg);
return {
reset: function() {
game.reset();
uciCmd('setoption name Contempt Factor value 0');
uciCmd('setoption name Skill Level value 20');
uciCmd('setoption name Aggressiveness value 100');
},
loadPgn: function(pgn) { game.load_pgn(pgn); },
setPlayerColor: function(color) {
playerColor = color;
board.orientation(playerColor);
},
setSkillLevel: function(skill) {
uciCmd('setoption name Skill Level value ' + skill);
},
setTime: function(baseTime, inc) {
time = { wtime: baseTime * 1000, btime: baseTime * 1000, winc: inc * 1000, binc: inc * 1000 };
},
setDepth: function(depth) {
time = { depth: depth };
},
setNodes: function(nodes) {
time = { nodes: nodes };
},
setContempt: function(contempt) {
uciCmd('setoption name Contempt Factor value ' + contempt);
},
setAggressiveness: function(value) {
uciCmd('setoption name Aggressiveness value ' + value);
},
setDisplayScore: function(flag) {
displayScore = flag;
displayStatus();
},
start: function() {
uciCmd('ucinewgame');
uciCmd('isready');
engineStatus.engineReady = false;
engineStatus.search = null;
displayStatus();
prepareMove();
},
undo: function() {
if(isEngineRunning)
return false;
game.undo();
game.undo();
engineStatus.search = null;
displayStatus();
prepareMove();
return true;
}
};
}