Commit | Line | Data |
---|---|---|
7ebc0408 | 1 | import { ChessRules } from "@/base_rules"; |
d54f6261 | 2 | import { randInt } from "@/utils/alea"; |
7ebc0408 BA |
3 | |
4 | export class SynchroneRules extends ChessRules { | |
d54f6261 | 5 | static get CanAnalyze() { |
d2844854 | 6 | return false; |
d54f6261 BA |
7 | } |
8 | ||
9 | static get ShowMoves() { | |
10 | return "byrow"; | |
11 | } | |
12 | ||
13 | static IsGoodFen(fen) { | |
14 | if (!ChessRules.IsGoodFen(fen)) return false; | |
15 | const fenParsed = V.ParseFen(fen); | |
16 | // 5) Check whiteMove | |
17 | if ( | |
18 | ( | |
9edfb714 | 19 | fenParsed.turn == "b" && |
d54f6261 BA |
20 | // NOTE: do not check really JSON stringified move... |
21 | (!fenParsed.whiteMove || fenParsed.whiteMove == "-") | |
22 | ) | |
23 | || | |
9edfb714 | 24 | (fenParsed.turn == "w" && fenParsed.whiteMove != "-") |
d54f6261 BA |
25 | ) { |
26 | return false; | |
27 | } | |
28 | return true; | |
29 | } | |
30 | ||
31 | static IsGoodEnpassant(enpassant) { | |
32 | const epArray = enpassant.split(","); | |
33 | if (![2, 3].includes(epArray.length)) return false; | |
34 | epArray.forEach(epsq => { | |
35 | if (epsq != "-") { | |
36 | const ep = V.SquareToCoords(epsq); | |
37 | if (isNaN(ep.x) || !V.OnBoard(ep)) return false; | |
38 | } | |
39 | }); | |
40 | return true; | |
41 | } | |
42 | ||
43 | static ParseFen(fen) { | |
44 | const fenParts = fen.split(" "); | |
45 | return Object.assign( | |
46 | ChessRules.ParseFen(fen), | |
47 | { whiteMove: fenParts[5] } | |
48 | ); | |
49 | } | |
50 | ||
51 | static GenRandInitFen(randomness) { | |
52 | return ChessRules.GenRandInitFen(randomness).slice(0, -1) + "-,- -"; | |
53 | } | |
54 | ||
55 | getFen() { | |
56 | return super.getFen() + " " + this.getWhitemoveFen(); | |
57 | } | |
58 | ||
59 | getFenForRepeat() { | |
60 | return super.getFenForRepeat() + "_" + this.getWhitemoveFen(); | |
61 | } | |
62 | ||
63 | setOtherVariables(fen) { | |
64 | const parsedFen = V.ParseFen(fen); | |
65 | this.setFlags(parsedFen.flags); | |
66 | const epArray = parsedFen.enpassant.split(","); | |
67 | this.epSquares = []; | |
68 | epArray.forEach(epsq => this.epSquares.push(this.getEpSquare(epsq))); | |
69 | super.scanKings(fen); | |
70 | // Also init whiteMove | |
71 | this.whiteMove = | |
72 | parsedFen.whiteMove != "-" | |
73 | ? JSON.parse(parsedFen.whiteMove) | |
74 | : null; | |
75 | } | |
76 | ||
77 | // After undo(): no need to re-set INIT_COL_KING | |
78 | scanKings() { | |
79 | this.kingPos = { w: [-1, -1], b: [-1, -1] }; | |
80 | for (let i = 0; i < V.size.x; i++) { | |
81 | for (let j = 0; j < V.size.y; j++) { | |
82 | if (this.getPiece(i, j) == V.KING) | |
83 | this.kingPos[this.getColor(i, j)] = [i, j]; | |
84 | } | |
85 | } | |
86 | } | |
87 | ||
88 | getEnpassantFen() { | |
89 | const L = this.epSquares.length; | |
90 | let res = ""; | |
91 | const start = L - 2 - (this.turn == 'b' ? 1 : 0); | |
92 | for (let i=start; i < L; i++) { | |
93 | if (!this.epSquares[i]) res += "-,"; | |
94 | else res += V.CoordsToSquare(this.epSquares[i]) + ","; | |
95 | } | |
96 | return res.slice(0, -1); | |
97 | } | |
98 | ||
99 | getWhitemoveFen() { | |
100 | if (!this.whiteMove) return "-"; | |
101 | return JSON.stringify({ | |
102 | start: this.whiteMove.start, | |
103 | end: this.whiteMove.end, | |
104 | appear: this.whiteMove.appear, | |
105 | vanish: this.whiteMove.vanish | |
106 | }); | |
107 | } | |
108 | ||
d54f6261 | 109 | getPossibleMovesFrom([x, y]) { |
d448f932 BA |
110 | let moves = this.filterValid(super.getPotentialMovesFrom([x, y])); |
111 | if (!this.underCheck(this.getColor(x, y))) | |
112 | // Augment with potential recaptures, except if we are under check | |
113 | Array.prototype.push.apply(moves, this.getRecaptures([x, y])); | |
114 | return moves; | |
d54f6261 BA |
115 | } |
116 | ||
6b9378a6 | 117 | // Aux function used to find opponent and self captures |
515ae62f | 118 | getCaptures(from, to, color) { |
d54f6261 | 119 | const sliderAttack = (xx, yy, allowedSteps) => { |
515ae62f | 120 | const deltaX = xx - to[0], |
d54f6261 | 121 | absDeltaX = Math.abs(deltaX); |
515ae62f | 122 | const deltaY = yy - to[1], |
d54f6261 BA |
123 | absDeltaY = Math.abs(deltaY); |
124 | const step = [ deltaX / absDeltaX || 0, deltaY / absDeltaY || 0 ]; | |
125 | if ( | |
126 | // Check that the step is a priori valid: | |
127 | (absDeltaX != absDeltaY && deltaX != 0 && deltaY != 0) || | |
128 | allowedSteps.every(st => st[0] != step[0] || st[1] != step[1]) | |
129 | ) { | |
130 | return null; | |
131 | } | |
515ae62f | 132 | let sq = [ to[0] + step[0], to[1] + step[1] ]; |
d54f6261 BA |
133 | while (sq[0] != xx || sq[1] != yy) { |
134 | // NOTE: no need to check OnBoard in this special case | |
135 | if (this.board[sq[0]][sq[1]] != V.EMPTY) return null; | |
136 | sq[0] += step[0]; | |
137 | sq[1] += step[1]; | |
138 | } | |
515ae62f | 139 | return this.getBasicMove([xx, yy], [to[0], to[1]]); |
d54f6261 | 140 | }; |
515ae62f | 141 | // Can I take on the square 'to' ? |
d54f6261 | 142 | // If yes, return the (list of) capturing move(s) |
515ae62f BA |
143 | const getTargetedCaptures = ([i, j]) => { |
144 | let move = null; | |
145 | // From [i, j]: | |
146 | switch (this.getPiece(i, j)) { | |
147 | case V.PAWN: { | |
148 | // Pushed pawns move as enemy pawns | |
149 | const shift = (color == 'w' ? 1 : -1); | |
150 | if (to[0] + shift == i && Math.abs(to[1] - j) == 1) | |
151 | move = this.getBasicMove([i, j], to); | |
152 | break; | |
153 | } | |
154 | case V.KNIGHT: { | |
155 | const deltaX = Math.abs(i - to[0]); | |
156 | const deltaY = Math.abs(j - to[1]); | |
157 | if ( | |
158 | deltaX + deltaY == 3 && | |
159 | [1, 2].includes(deltaX) && | |
160 | [1, 2].includes(deltaY) | |
161 | ) { | |
162 | move = this.getBasicMove([i, j], to); | |
163 | } | |
164 | break; | |
165 | } | |
166 | case V.KING: | |
167 | if (Math.abs(i - to[0]) <= 1 && Math.abs(j - to[1]) <= 1) | |
168 | move = this.getBasicMove([i, j], to); | |
169 | break; | |
170 | case V.ROOK: { | |
171 | move = sliderAttack(i, j, V.steps[V.ROOK]); | |
172 | break; | |
173 | } | |
174 | case V.BISHOP: { | |
175 | move = sliderAttack(i, j, V.steps[V.BISHOP]); | |
176 | break; | |
177 | } | |
178 | case V.QUEEN: { | |
179 | move = sliderAttack(i, j, V.steps[V.ROOK].concat(V.steps[V.BISHOP])); | |
180 | break; | |
181 | } | |
182 | } | |
183 | return move; | |
184 | }; | |
d54f6261 | 185 | let moves = []; |
515ae62f BA |
186 | if (!!from) { |
187 | const theMove = getTargetedCaptures(from); | |
188 | if (!!theMove) moves.push(theMove); | |
189 | } | |
190 | else { | |
191 | for (let i=0; i<8; i++) { | |
192 | for (let j=0; j<8; j++) { | |
193 | if (this.getColor(i, j) == color) { | |
194 | const newMove = getTargetedCaptures([i, j]); | |
195 | if (!!newMove) moves.push(newMove); | |
d54f6261 BA |
196 | } |
197 | } | |
198 | } | |
199 | } | |
200 | return this.filterValid(moves); | |
201 | } | |
202 | ||
515ae62f | 203 | getRecaptures(from) { |
6b9378a6 BA |
204 | // 1) Generate all opponent's capturing moves |
205 | let oppCaptureMoves = []; | |
1a3cfdc0 | 206 | const color = this.turn; |
6b9378a6 BA |
207 | const oppCol = V.GetOppCol(color); |
208 | for (let i=0; i<8; i++) { | |
209 | for (let j=0; j<8; j++) { | |
210 | if ( | |
211 | this.getColor(i, j) == color && | |
212 | // Do not consider king captures: self-captures of king are forbidden | |
213 | this.getPiece(i, j) != V.KING | |
214 | ) { | |
215 | Array.prototype.push.apply( | |
216 | oppCaptureMoves, | |
515ae62f | 217 | this.getCaptures(null, [i, j], oppCol) |
6b9378a6 BA |
218 | ); |
219 | } | |
220 | } | |
221 | } | |
222 | // 2) Play each opponent's capture, and see if back-captures are possible: | |
d54f6261 BA |
223 | // Lookup table to quickly decide if a move is already in list: |
224 | let moveSet = {}; | |
1a3cfdc0 | 225 | let moves = []; |
6b9378a6 | 226 | oppCaptureMoves.forEach(m => { |
2c5d7b20 | 227 | // If another opponent capture with same endpoint already processed, skip |
6b9378a6 BA |
228 | const mHash = "m" + m.end.x + m.end.y; |
229 | if (!moveSet[mHash]) { | |
230 | moveSet[mHash] = true; | |
231 | // Just make enemy piece disappear, to clear potential path: | |
232 | const justDisappear = { | |
233 | appear: [], | |
234 | vanish: [m.vanish[0]] | |
235 | }; | |
236 | V.PlayOnBoard(this.board, justDisappear); | |
237 | // Can I take on [m.end.x, m.end.y] ? If yes, add to list: | |
515ae62f | 238 | this.getCaptures(from, [m.end.x, m.end.y], color) |
2c5d7b20 | 239 | .forEach(cm => moves.push(cm)); |
6b9378a6 BA |
240 | V.UndoOnBoard(this.board, justDisappear); |
241 | } | |
d54f6261 | 242 | }); |
1a3cfdc0 BA |
243 | return moves; |
244 | } | |
245 | ||
246 | getAllValidMoves() { | |
247 | // Return possible moves + potential recaptures | |
248 | return super.getAllValidMoves().concat(this.getRecaptures()); | |
d54f6261 BA |
249 | } |
250 | ||
251 | filterValid(moves) { | |
252 | if (moves.length == 0) return []; | |
253 | // filterValid can be called when it's "not our turn": | |
254 | const color = moves[0].vanish[0].c; | |
255 | return moves.filter(m => { | |
256 | const piece = m.vanish[0].p; | |
257 | if (piece == V.KING) { | |
258 | this.kingPos[color][0] = m.appear[0].x; | |
259 | this.kingPos[color][1] = m.appear[0].y; | |
260 | } | |
261 | V.PlayOnBoard(this.board, m); | |
262 | let res = !this.underCheck(color); | |
263 | V.UndoOnBoard(this.board, m); | |
264 | if (piece == V.KING) this.kingPos[color] = [m.start.x, m.start.y]; | |
265 | return res; | |
266 | }); | |
267 | } | |
268 | ||
269 | atLeastOneMove(color) { | |
270 | const curTurn = this.turn; | |
271 | this.turn = color; | |
272 | const res = super.atLeastOneMove(); | |
273 | this.turn = curTurn; | |
274 | return res; | |
275 | } | |
276 | ||
277 | // White and black (partial) moves were played: merge | |
278 | resolveSynchroneMove(move) { | |
279 | const m1 = this.whiteMove; | |
280 | const m2 = move; | |
281 | // For PlayOnBoard (no need for start / end, irrelevant) | |
282 | let smove = { | |
283 | appear: [], | |
284 | vanish: [ | |
285 | m1.vanish[0], | |
286 | m2.vanish[0] | |
287 | ] | |
288 | }; | |
289 | if ((m1.end.x != m2.end.x) || (m1.end.y != m2.end.y)) { | |
290 | // Easy case: two independant moves (which may (self-)capture) | |
291 | smove.appear.push(m1.appear[0]); | |
292 | smove.appear.push(m2.appear[0]); | |
293 | // "Captured" pieces may have moved: | |
6b9378a6 BA |
294 | if (m1.appear.length == 2) { |
295 | // Castle | |
296 | smove.appear.push(m1.appear[1]); | |
297 | smove.vanish.push(m1.vanish[1]); | |
298 | } else if ( | |
d54f6261 BA |
299 | m1.vanish.length == 2 && |
300 | ( | |
6b9378a6 BA |
301 | m1.vanish[1].x != m2.start.x || |
302 | m1.vanish[1].y != m2.start.y | |
d54f6261 BA |
303 | ) |
304 | ) { | |
305 | smove.vanish.push(m1.vanish[1]); | |
306 | } | |
6b9378a6 BA |
307 | if (m2.appear.length == 2) { |
308 | // Castle | |
309 | smove.appear.push(m2.appear[1]); | |
310 | smove.vanish.push(m2.vanish[1]); | |
311 | } else if ( | |
d54f6261 BA |
312 | m2.vanish.length == 2 && |
313 | ( | |
6b9378a6 BA |
314 | m2.vanish[1].x != m1.start.x || |
315 | m2.vanish[1].y != m1.start.y | |
d54f6261 BA |
316 | ) |
317 | ) { | |
318 | smove.vanish.push(m2.vanish[1]); | |
319 | } | |
320 | } else { | |
321 | // Collision: | |
322 | if (m1.vanish.length == 1 && m2.vanish.length == 1) { | |
323 | // Easy case: both disappear except if one is a king | |
324 | const p1 = m1.vanish[0].p; | |
325 | const p2 = m2.vanish[0].p; | |
326 | if ([p1, p2].includes(V.KING)) { | |
327 | smove.appear.push({ | |
328 | x: m1.end.x, | |
329 | y: m1.end.y, | |
330 | p: V.KING, | |
331 | c: (p1 == V.KING ? 'w' : 'b') | |
332 | }); | |
333 | } | |
334 | } else { | |
335 | // One move is a self-capture and the other a normal capture: | |
336 | // only the self-capture appears | |
d54f6261 BA |
337 | const selfCaptureMove = |
338 | m1.vanish[1].c == m1.vanish[0].c | |
339 | ? m1 | |
340 | : m2; | |
341 | smove.appear.push({ | |
342 | x: m1.end.x, | |
343 | y: m1.end.y, | |
344 | p: selfCaptureMove.appear[0].p, | |
345 | c: selfCaptureMove.vanish[0].c | |
346 | }); | |
6b9378a6 BA |
347 | smove.vanish.push({ |
348 | x: m1.end.x, | |
349 | y: m1.end.y, | |
350 | p: selfCaptureMove.vanish[1].p, | |
351 | c: selfCaptureMove.vanish[0].c | |
352 | }); | |
d54f6261 BA |
353 | } |
354 | } | |
355 | return smove; | |
356 | } | |
357 | ||
358 | play(move) { | |
359 | move.flags = JSON.stringify(this.aggregateFlags()); //save flags (for undo) | |
360 | this.epSquares.push(this.getEpSquare(move)); | |
361 | // Do not play on board (would reveal the move...) | |
362 | this.turn = V.GetOppCol(this.turn); | |
363 | this.movesCount++; | |
364 | this.postPlay(move); | |
365 | } | |
366 | ||
367 | updateCastleFlags(move) { | |
368 | const firstRank = { 'w': V.size.x - 1, 'b': 0 }; | |
369 | move.appear.concat(move.vanish).forEach(av => { | |
370 | for (let c of ['w', 'b']) { | |
371 | if (av.x == firstRank[c] && this.castleFlags[c].includes(av.y)) { | |
372 | const flagIdx = (av.y == this.castleFlags[c][0] ? 0 : 1); | |
373 | this.castleFlags[c][flagIdx] = 8; | |
374 | } | |
375 | } | |
376 | }); | |
377 | } | |
378 | ||
379 | postPlay(move) { | |
380 | if (this.turn == 'b') { | |
381 | // NOTE: whiteMove is used read-only, so no need to copy | |
382 | this.whiteMove = move; | |
383 | return; | |
384 | } | |
385 | ||
386 | // A full turn just ended: | |
387 | const smove = this.resolveSynchroneMove(move); | |
388 | V.PlayOnBoard(this.board, smove); | |
6b9378a6 | 389 | move.whiteMove = this.whiteMove; //for undo |
d54f6261 BA |
390 | this.whiteMove = null; |
391 | ||
392 | // Update king position + flags | |
393 | let kingAppear = { 'w': false, 'b': false }; | |
394 | for (let i=0; i<smove.appear.length; i++) { | |
395 | if (smove.appear[i].p == V.KING) { | |
396 | const c = smove.appear[i].c; | |
397 | kingAppear[c] = true; | |
398 | this.kingPos[c][0] = smove.appear[i].x; | |
399 | this.kingPos[c][1] = smove.appear[i].y; | |
400 | } | |
401 | } | |
402 | for (let i=0; i<smove.vanish.length; i++) { | |
403 | if (smove.vanish[i].p == V.KING) { | |
404 | const c = smove.vanish[i].c; | |
405 | if (!kingAppear[c]) { | |
406 | this.kingPos[c][0] = -1; | |
407 | this.kingPos[c][1] = -1; | |
408 | } | |
409 | break; | |
410 | } | |
411 | } | |
412 | this.updateCastleFlags(smove); | |
413 | move.smove = smove; | |
414 | } | |
415 | ||
416 | undo(move) { | |
417 | this.epSquares.pop(); | |
418 | this.disaggregateFlags(JSON.parse(move.flags)); | |
419 | if (this.turn == 'w') | |
420 | // Back to the middle of the move | |
421 | V.UndoOnBoard(this.board, move.smove); | |
422 | this.turn = V.GetOppCol(this.turn); | |
423 | this.movesCount--; | |
424 | this.postUndo(move); | |
425 | } | |
426 | ||
427 | postUndo(move) { | |
6b9378a6 | 428 | if (this.turn == 'w') { |
d54f6261 BA |
429 | // Reset king positions: scan board |
430 | this.scanKings(); | |
6b9378a6 BA |
431 | // Also reset whiteMove |
432 | this.whiteMove = null; | |
433 | } else this.whiteMove = move.whiteMove; | |
d54f6261 BA |
434 | } |
435 | ||
af34341d BA |
436 | getCheckSquares() { |
437 | const color = this.turn; | |
6b9378a6 BA |
438 | if (color == 'b') { |
439 | // kingPos must be reset for appropriate highlighting: | |
440 | var lastMove = JSON.parse(JSON.stringify(this.whiteMove)); | |
441 | this.undo(lastMove); //will erase whiteMove, thus saved above | |
442 | } | |
d54f6261 | 443 | let res = []; |
1a3cfdc0 | 444 | if (this.kingPos['w'][0] >= 0 && this.underCheck('w')) |
d54f6261 | 445 | res.push(JSON.parse(JSON.stringify(this.kingPos['w']))); |
1a3cfdc0 | 446 | if (this.kingPos['b'][0] >= 0 && this.underCheck('b')) |
d54f6261 | 447 | res.push(JSON.parse(JSON.stringify(this.kingPos['b']))); |
6b9378a6 | 448 | if (color == 'b') this.play(lastMove); |
d54f6261 BA |
449 | return res; |
450 | } | |
451 | ||
452 | getCurrentScore() { | |
453 | if (this.turn == 'b') | |
454 | // Turn (white + black) not over yet | |
455 | return "*"; | |
456 | // Was a king captured? | |
457 | if (this.kingPos['w'][0] < 0) return "0-1"; | |
458 | if (this.kingPos['b'][0] < 0) return "1-0"; | |
459 | const whiteCanMove = this.atLeastOneMove('w'); | |
460 | const blackCanMove = this.atLeastOneMove('b'); | |
461 | if (whiteCanMove && blackCanMove) return "*"; | |
462 | // Game over | |
463 | const whiteInCheck = this.underCheck('w'); | |
464 | const blackInCheck = this.underCheck('b'); | |
465 | if ( | |
466 | (whiteCanMove && !this.underCheck('b')) || | |
467 | (blackCanMove && !this.underCheck('w')) | |
468 | ) { | |
469 | return "1/2"; | |
470 | } | |
471 | // Checkmate: could be mutual | |
472 | if (!whiteCanMove && !blackCanMove) return "1/2"; | |
473 | return (whiteCanMove ? "1-0" : "0-1"); | |
474 | } | |
475 | ||
476 | getComputerMove() { | |
477 | const maxeval = V.INFINITY; | |
478 | const color = this.turn; | |
479 | let moves = this.getAllValidMoves(); | |
480 | if (moves.length == 0) | |
481 | // TODO: this situation should not happen | |
482 | return null; | |
483 | ||
484 | if (Math.random() < 0.5) | |
485 | // Return a random move | |
486 | return moves[randInt(moves.length)]; | |
487 | ||
488 | // Rank moves at depth 1: | |
489 | // try to capture something (not re-capturing) | |
490 | moves.forEach(m => { | |
491 | V.PlayOnBoard(this.board, m); | |
492 | m.eval = this.evalPosition(); | |
493 | V.UndoOnBoard(this.board, m); | |
494 | }); | |
495 | moves.sort((a, b) => { | |
496 | return (color == "w" ? 1 : -1) * (b.eval - a.eval); | |
497 | }); | |
498 | let candidates = [0]; | |
499 | for (let i = 1; i < moves.length && moves[i].eval == moves[0].eval; i++) | |
500 | candidates.push(i); | |
501 | return moves[candidates[randInt(candidates.length)]]; | |
502 | } | |
6b9378a6 BA |
503 | |
504 | getNotation(move) { | |
505 | if (move.appear.length == 2 && move.appear[0].p == V.KING) | |
506 | // Castle | |
507 | return move.end.y < move.start.y ? "0-0-0" : "0-0"; | |
508 | // Basic system: piece + init + dest square | |
509 | return ( | |
510 | move.vanish[0].p.toUpperCase() + | |
511 | V.CoordsToSquare(move.start) + | |
512 | V.CoordsToSquare(move.end) | |
513 | ); | |
514 | } | |
7ebc0408 | 515 | }; |