Commit | Line | Data |
---|---|---|
9d15c433 BA |
1 | import { ChessRules, PiPo, Move } from "@/base_rules"; |
2 | import { randInt } from "@/utils/alea"; | |
3 | import { ArrayFun } from "@/utils/array"; | |
4 | ||
5 | export class OtageRules extends ChessRules { | |
6 | ||
7 | static get IMAGE_EXTENSION() { | |
8 | return ".png"; | |
9 | } | |
10 | ||
11 | // Hostage / Capturer combinations | |
12 | // + letter among a, b, v, w to indicate colors + config: | |
13 | // a: black first, black controls | |
14 | // b: white first, black controls | |
15 | // v: black first, white controls | |
16 | // w: white first, white controls | |
17 | static get UNIONS() { | |
18 | return { | |
19 | a: ['p', 'p'], | |
20 | c: ['p', 'r'], | |
21 | d: ['p', 'n'], | |
22 | e: ['p', 'b'], | |
23 | f: ['p', 'q'], | |
24 | g: ['p', 'k'], | |
25 | h: ['r', 'r'], | |
26 | i: ['r', 'n'], | |
27 | j: ['r', 'b'], | |
28 | l: ['r', 'q'], | |
29 | m: ['r', 'k'], | |
30 | o: ['n', 'n'], | |
31 | s: ['n', 'b'], | |
32 | t: ['n', 'q'], | |
33 | u: ['n', 'k'], | |
34 | v: ['b', 'b'], | |
35 | w: ['b', 'q'], | |
36 | x: ['b', 'k'], | |
37 | y: ['q', 'q'], | |
38 | z: ['q', 'k'], | |
39 | '_': ['k', 'k'] | |
40 | }; | |
41 | } | |
42 | ||
43 | static board2fen(b) { | |
44 | if (ChessRules.PIECES.includes(b[1])) return ChessRules.board2fen(b); | |
45 | // Show symbol first (no collisions) | |
46 | return b[1] + b[0]; | |
47 | } | |
48 | ||
49 | static fen2board(f) { | |
50 | if (f.length == 1) return ChessRules.fen2board(f); | |
51 | return f[1] + f[0]; //"color" first | |
52 | } | |
53 | ||
54 | static IsGoodPosition(position) { | |
55 | if (position.length == 0) return false; | |
56 | const rows = position.split("/"); | |
57 | if (rows.length != V.size.x) return false; | |
9d15c433 BA |
58 | let kings = { 'k': 0, 'K': 0 }; |
59 | for (let row of rows) { | |
60 | let sumElts = 0; | |
61 | for (let i = 0; i < row.length; i++) { | |
8ec71052 | 62 | const lowR = row[i].toLowerCase(); |
9d15c433 BA |
63 | const readNext = !(ChessRules.PIECES.includes(lowR)); |
64 | if (!!(lowR.match(/[a-z_]/))) { | |
65 | sumElts++; | |
8ec71052 BA |
66 | if (lowR == 'k') kings[row[i]]++; |
67 | else if (readNext) { | |
68 | const up = this.getUnionPieces(row[++i], lowR); | |
69 | if (up.w == V.KING) kings['K']++; | |
70 | // NOTE: not "else if" because two kings might be in union | |
71 | if (up.b == V.KING) kings['k']++; | |
72 | } | |
9d15c433 BA |
73 | } |
74 | else { | |
75 | const num = parseInt(row[i], 10); | |
76 | if (isNaN(num) || num <= 0) return false; | |
77 | sumElts += num; | |
78 | } | |
79 | } | |
80 | if (sumElts != V.size.y) return false; | |
81 | } | |
82 | // Both kings should be on board. Exactly one per color. | |
83 | if (Object.values(kings).some(v => v != 1)) return false; | |
84 | return true; | |
85 | } | |
86 | ||
87 | static GetBoard(position) { | |
88 | const rows = position.split("/"); | |
89 | let board = ArrayFun.init(V.size.x, V.size.y, ""); | |
90 | for (let i = 0; i < rows.length; i++) { | |
91 | let j = 0; | |
92 | for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) { | |
93 | const character = rows[i][indexInRow]; | |
94 | const num = parseInt(character, 10); | |
95 | // If num is a number, just shift j: | |
96 | if (!isNaN(num)) j += num; | |
97 | else { | |
98 | // Something at position i,j | |
99 | const lowC = character.toLowerCase(); | |
100 | if (ChessRules.PIECES.includes(lowC)) | |
101 | board[i][j++] = V.fen2board(character); | |
102 | else | |
103 | board[i][j++] = V.fen2board(lowC + rows[i][++indexInRow]); | |
104 | } | |
105 | } | |
106 | } | |
107 | return board; | |
108 | } | |
109 | ||
110 | getPpath(b) { | |
111 | return "Otage/" + b; | |
112 | } | |
113 | ||
114 | getPPpath(m) { | |
115 | if (ChessRules.PIECES.includes(m.appear[0].p)) return super.getPPpath(m); | |
116 | // For an "union", show only relevant piece: | |
117 | // The color must be deduced from the move: reaching final rank of who? | |
118 | const color = (m.appear[0].x == 0 ? 'w' : 'b'); | |
119 | const up = this.getUnionPieces(m.appear[0].c, m.appear[0].p); | |
120 | return "Pacosako/" + color + up[color]; | |
121 | } | |
122 | ||
123 | canTake([x1, y1], [x2, y2]) { | |
124 | const p1 = this.board[x1][y1].charAt(1); | |
125 | if (!(ChessRules.PIECES.includes(p1))) return false; | |
126 | const p2 = this.board[x2][y2].charAt(1); | |
127 | if (!(ChessRules.PIECES.includes(p2))) return true; | |
128 | const c1 = this.board[x1][y1].charAt(0); | |
129 | const c2 = this.board[x2][y2].charAt(0); | |
130 | return (c1 != c2); | |
131 | } | |
132 | ||
133 | canIplay(side, [x, y]) { | |
134 | const c = this.board[x][y].charAt(0); | |
135 | const compSide = (side == 'w' ? 'v' : 'a'); | |
136 | return (this.turn == side && [side, compSide].includes(c)); | |
137 | } | |
138 | ||
139 | scanKings(fen) { | |
140 | this.kingPos = { w: [-1, -1], b: [-1, -1] }; | |
141 | const fenRows = V.ParseFen(fen).position.split("/"); | |
142 | const startRow = { 'w': V.size.x - 1, 'b': 0 }; | |
9d15c433 BA |
143 | for (let i = 0; i < fenRows.length; i++) { |
144 | let k = 0; | |
145 | for (let j = 0; j < fenRows[i].length; j++) { | |
146 | const c = fenRows[i].charAt(j); | |
147 | const lowR = c.toLowerCase(); | |
148 | const readNext = !(ChessRules.PIECES.includes(lowR)); | |
149 | if (!!(lowR.match(/[a-z_]/))) { | |
8ec71052 BA |
150 | if (lowR == 'k') this.kingPos[c == 'k' ? 'b' : 'w'] = [i, k]; |
151 | else if (readNext) { | |
152 | const up = this.getUnionPieces(fenRows[i][++j], lowR); | |
153 | if (up.w == V.KING) this.kingPos['w'] = [i, k]; | |
154 | if (up.b == V.KING) this.kingPos['b'] = [i, k]; | |
155 | } | |
9d15c433 BA |
156 | } |
157 | else { | |
158 | const num = parseInt(fenRows[i].charAt(j), 10); | |
159 | if (!isNaN(num)) k += num - 1; | |
160 | } | |
161 | k++; | |
162 | } | |
163 | } | |
164 | } | |
165 | ||
166 | setOtherVariables(fen) { | |
167 | super.setOtherVariables(fen); | |
168 | // Stack of "last move" only for intermediate chaining | |
169 | this.lastMoveEnd = [null]; | |
f3f84707 | 170 | this.repetitions = []; |
9d15c433 BA |
171 | } |
172 | ||
173 | static IsGoodFlags(flags) { | |
174 | // 4 for castle + 16 for pawns | |
175 | return !!flags.match(/^[a-z]{4,4}[01]{16,16}$/); | |
176 | } | |
177 | ||
178 | setFlags(fenflags) { | |
179 | super.setFlags(fenflags); //castleFlags | |
180 | this.pawnFlags = { | |
181 | w: [...Array(8)], //pawns can move 2 squares? | |
182 | b: [...Array(8)] | |
183 | }; | |
184 | const flags = fenflags.substr(4); //skip first 4 letters, for castle | |
185 | for (let c of ["w", "b"]) { | |
186 | for (let i = 0; i < 8; i++) | |
187 | this.pawnFlags[c][i] = flags.charAt((c == "w" ? 0 : 8) + i) == "1"; | |
188 | } | |
189 | } | |
190 | ||
191 | aggregateFlags() { | |
192 | return [this.castleFlags, this.pawnFlags]; | |
193 | } | |
194 | ||
195 | disaggregateFlags(flags) { | |
196 | this.castleFlags = flags[0]; | |
197 | this.pawnFlags = flags[1]; | |
198 | } | |
199 | ||
200 | static GenRandInitFen(randomness) { | |
201 | // Add 16 pawns flags: | |
202 | return ChessRules.GenRandInitFen(randomness) | |
203 | .slice(0, -2) + "1111111111111111 -"; | |
204 | } | |
205 | ||
206 | getFlagsFen() { | |
207 | let fen = super.getFlagsFen(); | |
208 | // Add pawns flags | |
209 | for (let c of ["w", "b"]) | |
210 | for (let i = 0; i < 8; i++) fen += (this.pawnFlags[c][i] ? "1" : "0"); | |
211 | return fen; | |
212 | } | |
213 | ||
214 | getPiece(i, j) { | |
215 | const p = this.board[i][j].charAt(1); | |
216 | if (ChessRules.PIECES.includes(p)) return p; | |
217 | const c = this.board[i][j].charAt(0); | |
218 | const idx = (['a', 'w'].includes(c) ? 0 : 1); | |
219 | return V.UNIONS[p][idx]; | |
220 | } | |
221 | ||
222 | getUnionPieces(color, code) { | |
223 | const pieces = V.UNIONS[code]; | |
224 | return { | |
225 | w: pieces[ ['b', 'w'].includes(color) ? 0 : 1 ], | |
226 | b: pieces[ ['a', 'v'].includes(color) ? 0 : 1 ] | |
227 | }; | |
228 | } | |
229 | ||
230 | // p1: white piece, p2: black piece, capturer: (temporary) owner | |
231 | getUnionCode(p1, p2, capturer) { | |
232 | let uIdx = ( | |
233 | Object.values(V.UNIONS).findIndex(v => v[0] == p1 && v[1] == p2) | |
234 | ); | |
235 | let c = ''; | |
236 | if (capturer == 'w') c = (uIdx >= 0 ? 'w' : 'v'); | |
237 | else c = (uIdx >= 0 ? 'b' : 'a'); | |
238 | if (uIdx == -1) { | |
239 | uIdx = ( | |
240 | Object.values(V.UNIONS).findIndex(v => v[0] == p2 && v[1] == p1) | |
241 | ); | |
242 | } | |
243 | return { c: c, p: Object.keys(V.UNIONS)[uIdx] }; | |
244 | } | |
245 | ||
246 | getBasicMove([sx, sy], [ex, ey], tr) { | |
247 | const L = this.lastMoveEnd.length; | |
248 | const lm = this.lastMoveEnd[L-1]; | |
249 | const piece = (!!lm ? lm.p : null); | |
250 | const initColor = (!!piece ? this.turn : this.board[sx][sy].charAt(0)); | |
251 | const initPiece = (piece || this.board[sx][sy].charAt(1)); | |
252 | const c = this.turn; | |
253 | const oppCol = V.GetOppCol(c); | |
254 | if (!!tr && !(ChessRules.PIECES.includes(initPiece))) { | |
255 | // Transformation computed without taking union into account | |
256 | const up = this.getUnionPieces(initColor, initPiece); | |
257 | let args = [tr.p, up[oppCol]]; | |
258 | if (['a', 'v'].includes(initColor)) args = args.reverse(); | |
259 | const capturer = (['a', 'b'].includes(initColor) ? 'b' : 'w'); | |
260 | const cp = this.getUnionCode(args[0], args[1], capturer); | |
261 | tr.c = cp.c; | |
262 | tr.p = cp.p; | |
263 | } | |
264 | // 4 cases : moving | |
265 | // - union to free square (other cases are illegal: return null) | |
266 | // - normal piece to free square, | |
267 | // to enemy normal piece, or | |
268 | // to union (releasing our piece) | |
269 | let mv = new Move({ | |
270 | start: { x: sx, y: sy }, | |
271 | end: { x: ex, y: ey }, | |
272 | vanish: [] | |
273 | }); | |
274 | if (!piece) { | |
275 | mv.vanish = [ | |
276 | new PiPo({ | |
277 | x: sx, | |
278 | y: sy, | |
279 | c: initColor, | |
280 | p: initPiece | |
281 | }) | |
282 | ]; | |
283 | } | |
284 | // Treat free square cases first: | |
285 | if (this.board[ex][ey] == V.EMPTY) { | |
286 | mv.appear = [ | |
287 | new PiPo({ | |
288 | x: ex, | |
289 | y: ey, | |
290 | c: !!tr ? tr.c : initColor, | |
291 | p: !!tr ? tr.p : initPiece | |
292 | }) | |
293 | ]; | |
294 | return mv; | |
295 | } | |
296 | // Now the two cases with union / release: | |
297 | const destColor = this.board[ex][ey].charAt(0); | |
298 | const destPiece = this.board[ex][ey].charAt(1); | |
299 | mv.vanish.push( | |
300 | new PiPo({ | |
301 | x: ex, | |
302 | y: ey, | |
303 | c: destColor, | |
304 | p: destPiece | |
305 | }) | |
306 | ); | |
307 | if (ChessRules.PIECES.includes(destPiece)) { | |
308 | // Normal piece: just create union | |
309 | let args = [!!tr ? tr.p : initPiece, destPiece]; | |
310 | if (c == 'b') args = args.reverse(); | |
311 | const cp = this.getUnionCode(args[0], args[1], c); | |
312 | mv.appear = [ | |
313 | new PiPo({ | |
314 | x: ex, | |
315 | y: ey, | |
316 | c: cp.c, | |
317 | p: cp.p | |
318 | }) | |
319 | ]; | |
320 | return mv; | |
321 | } | |
322 | // Releasing a piece in an union: keep track of released piece | |
323 | const up = this.getUnionPieces(destColor, destPiece); | |
324 | let args = [!!tr ? tr.p : initPiece, up[oppCol]]; | |
325 | if (c == 'b') args = args.reverse(); | |
326 | const cp = this.getUnionCode(args[0], args[1], c); | |
327 | mv.appear = [ | |
328 | new PiPo({ | |
329 | x: ex, | |
330 | y: ey, | |
331 | c: cp.c, | |
332 | p: cp.p | |
333 | }) | |
334 | ]; | |
335 | mv.end.released = up[c]; | |
336 | return mv; | |
337 | } | |
338 | ||
339 | // noCastle arg: when detecting king attacks | |
340 | getPotentialMovesFrom([x, y], noCastle) { | |
341 | const L = this.lastMoveEnd.length; | |
342 | const lm = this.lastMoveEnd[L-1]; | |
343 | if (!!lm && (x != lm.x || y != lm.y)) return []; | |
344 | const piece = (!!lm ? lm.p : this.getPiece(x, y)); | |
345 | if (!!lm) { | |
346 | var saveSquare = this.board[x][y]; | |
347 | this.board[x][y] = this.turn + piece; | |
348 | } | |
349 | let baseMoves = []; | |
350 | const c = this.turn; | |
351 | switch (piece || this.getPiece(x, y)) { | |
352 | case V.PAWN: { | |
353 | const firstRank = (c == 'w' ? 7 : 0); | |
354 | baseMoves = this.getPotentialPawnMoves([x, y]).filter(m => { | |
355 | // Skip forbidden 2-squares jumps (except from first rank) | |
356 | // Also skip unions capturing en-passant (not allowed). | |
357 | return ( | |
358 | ( | |
359 | m.start.x == firstRank || | |
360 | Math.abs(m.end.x - m.start.x) == 1 || | |
361 | this.pawnFlags[c][m.start.y] | |
362 | ) | |
363 | && | |
364 | ( | |
365 | this.board[x][y].charAt(1) == V.PAWN || | |
366 | m.start.y == m.end.y | |
367 | ) | |
368 | ); | |
369 | }); | |
370 | break; | |
371 | } | |
372 | case V.ROOK: | |
373 | baseMoves = this.getPotentialRookMoves([x, y]); | |
374 | break; | |
375 | case V.KNIGHT: | |
376 | baseMoves = this.getPotentialKnightMoves([x, y]); | |
377 | break; | |
378 | case V.BISHOP: | |
379 | baseMoves = this.getPotentialBishopMoves([x, y]); | |
380 | break; | |
381 | case V.QUEEN: | |
382 | baseMoves = this.getPotentialQueenMoves([x, y]); | |
383 | break; | |
384 | case V.KING: | |
385 | baseMoves = this.getSlideNJumpMoves( | |
ca4d732a | 386 | [x, y], |
9d15c433 BA |
387 | V.steps[V.ROOK].concat(V.steps[V.BISHOP]), |
388 | "oneStep" | |
389 | ); | |
390 | if (!noCastle && this.castleFlags[this.turn].some(v => v < V.size.y)) | |
8a8687b8 | 391 | baseMoves = baseMoves.concat(this.getCastleMoves([x, y])); |
9d15c433 BA |
392 | break; |
393 | } | |
394 | // When a pawn in an union reaches final rank with a non-standard | |
395 | // promotion move: apply promotion anyway | |
396 | let moves = []; | |
397 | const oppCol = V.GetOppCol(c); | |
398 | const oppLastRank = (c == 'w' ? 7 : 0); | |
399 | baseMoves.forEach(m => { | |
400 | if ( | |
401 | m.end.x == oppLastRank && | |
402 | ['c', 'd', 'e', 'f', 'g'].includes(m.appear[0].p) | |
403 | ) { | |
404 | // Move to first rank, which is last rank for opponent's pawn. | |
405 | // => Show promotion choices. | |
406 | // Find our piece in union (not a pawn) | |
407 | const up = this.getUnionPieces(m.appear[0].c, m.appear[0].p); | |
408 | // merge with all potential promotion pieces + push (loop) | |
409 | for (let promotionPiece of [V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN]) { | |
410 | let args = [up[c], promotionPiece]; | |
411 | if (c == 'b') args = args.reverse(); | |
412 | const cp = this.getUnionCode(args[0], args[1], c); | |
413 | let cpMove = JSON.parse(JSON.stringify(m)); | |
414 | cpMove.appear[0].c = cp.c; | |
415 | cpMove.appear[0].p = cp.p; | |
416 | moves.push(cpMove); | |
417 | } | |
418 | } | |
419 | else { | |
420 | if ( | |
421 | m.vanish.length > 0 && | |
422 | m.vanish[0].p == V.PAWN && | |
423 | m.start.y != m.end.y && | |
424 | this.board[m.end.x][m.end.y] == V.EMPTY | |
425 | ) { | |
426 | if (!!lm) | |
427 | // No en-passant inside a chaining | |
428 | return; | |
429 | // Fix en-passant capture: union type, maybe released piece too | |
430 | const cs = [m.end.x + (c == 'w' ? 1 : -1), m.end.y]; | |
431 | const code = this.board[cs[0]][cs[1]].charAt(1); | |
432 | if (code == V.PAWN) { | |
433 | // Simple en-passant capture (usual: just form union) | |
434 | m.appear[0].c = c; | |
435 | m.appear[0].p = 'a'; | |
436 | } | |
437 | else { | |
438 | // An union pawn + something just moved two squares | |
439 | const color = this.board[cs[0]][cs[1]].charAt(0); | |
440 | const up = this.getUnionPieces(color, code); | |
441 | m.end.released = up[c]; | |
442 | let args = [V.PAWN, up[oppCol]]; | |
443 | if (c == 'b') args = args.reverse(); | |
444 | const cp = this.getUnionCode(args[0], args[1], c); | |
445 | m.appear[0].c = cp.c; | |
446 | m.appear[0].p = cp.p; | |
447 | } | |
448 | } | |
449 | moves.push(m); | |
450 | } | |
451 | }); | |
452 | if (!!lm) this.board[x][y] = saveSquare; | |
453 | return moves; | |
454 | } | |
455 | ||
456 | getEpSquare(moveOrSquare) { | |
457 | if (typeof moveOrSquare === "string") { | |
458 | const square = moveOrSquare; | |
459 | if (square == "-") return undefined; | |
460 | return V.SquareToCoords(square); | |
461 | } | |
462 | const move = moveOrSquare; | |
463 | const s = move.start, | |
464 | e = move.end; | |
465 | if ( | |
466 | s.y == e.y && | |
467 | Math.abs(s.x - e.x) == 2 && | |
468 | this.getPiece(s.x, s.y) == V.PAWN | |
469 | ) { | |
470 | return { | |
471 | x: (s.x + e.x) / 2, | |
472 | y: s.y | |
473 | }; | |
474 | } | |
475 | return undefined; | |
476 | } | |
477 | ||
478 | getCastleMoves([x, y]) { | |
479 | const c = this.turn; | |
480 | const accepted = (c == 'w' ? ['v', 'w'] : ['a', 'b']); | |
481 | const oppCol = V.GetOppCol(c); | |
482 | let moves = []; | |
483 | const finalSquares = [ [2, 3], [6, 5] ]; | |
484 | castlingCheck: for (let castleSide = 0; castleSide < 2; castleSide++) { | |
485 | if (this.castleFlags[c][castleSide] >= 8) continue; | |
486 | const rookPos = this.castleFlags[c][castleSide]; | |
487 | const castlingColor = this.board[x][rookPos].charAt(0); | |
488 | const castlingPiece = this.board[x][rookPos].charAt(1); | |
489 | ||
490 | // Nothing on the path of the king ? | |
491 | const finDist = finalSquares[castleSide][0] - y; | |
492 | let step = finDist / Math.max(1, Math.abs(finDist)); | |
493 | let i = y; | |
494 | let kingSquares = [y]; | |
495 | do { | |
496 | if ( | |
497 | this.board[x][i] != V.EMPTY && | |
498 | !accepted.includes(this.getColor(x, i)) | |
499 | ) { | |
500 | continue castlingCheck; | |
501 | } | |
502 | i += step; | |
503 | kingSquares.push(i); | |
504 | } while (i != finalSquares[castleSide][0]); | |
505 | // No checks on the path of the king ? | |
506 | if (this.isAttacked(kingSquares, oppCol)) continue castlingCheck; | |
507 | ||
508 | // Nothing on the path to the rook? | |
509 | step = castleSide == 0 ? -1 : 1; | |
510 | for (i = y + step; i != rookPos; i += step) { | |
511 | if (this.board[x][i] != V.EMPTY) continue castlingCheck; | |
512 | } | |
513 | ||
514 | // Nothing on final squares, except maybe king and castling rook? | |
515 | for (i = 0; i < 2; i++) { | |
516 | if ( | |
517 | finalSquares[castleSide][i] != rookPos && | |
518 | this.board[x][finalSquares[castleSide][i]] != V.EMPTY && | |
519 | ( | |
520 | finalSquares[castleSide][i] != y || | |
521 | // TODO: next test seems superflu | |
522 | !accepted.includes(this.getColor(x, finalSquares[castleSide][i])) | |
523 | ) | |
524 | ) { | |
525 | continue castlingCheck; | |
526 | } | |
527 | } | |
528 | ||
529 | moves.push( | |
530 | new Move({ | |
531 | appear: [ | |
532 | new PiPo({ | |
533 | x: x, | |
534 | y: finalSquares[castleSide][0], | |
535 | p: V.KING, | |
536 | c: c | |
537 | }), | |
538 | new PiPo({ | |
539 | x: x, | |
540 | y: finalSquares[castleSide][1], | |
541 | p: castlingPiece, | |
542 | c: castlingColor | |
543 | }) | |
544 | ], | |
545 | vanish: [ | |
546 | // King might be initially disguised (Titan...) | |
547 | new PiPo({ x: x, y: y, p: V.KING, c: c }), | |
548 | new PiPo({ x: x, y: rookPos, p: castlingPiece, c: castlingColor }) | |
549 | ], | |
550 | end: | |
551 | Math.abs(y - rookPos) <= 2 | |
552 | ? { x: x, y: rookPos } | |
553 | : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) } | |
554 | }) | |
555 | ); | |
556 | } | |
557 | ||
558 | return moves; | |
559 | } | |
560 | ||
561 | getEnpassantCaptures(sq, shiftX) { | |
562 | // HACK: when artificially change turn, do not consider en-passant | |
563 | const mcMod2 = this.movesCount % 2; | |
564 | const c = this.turn; | |
565 | if ((c == 'w' && mcMod2 == 1) || (c == 'b' && mcMod2 == 0)) return []; | |
566 | return super.getEnpassantCaptures(sq, shiftX); | |
567 | } | |
568 | ||
569 | isAttacked_aux(files, color, positions, fromSquare, released) { | |
570 | // "positions" = array of FENs to detect infinite loops. Example: | |
571 | // r1q1k2r/p1Pb1ppp/5n2/1f1p4/AV5P/P1eDP3/3B1PP1/R3K1NR, | |
572 | // Bxd2 Bxc3 Bxb4 Bxc3 Bxb4 etc. | |
573 | const newPos = { fen: super.getBaseFen(), piece: released }; | |
574 | if (positions.some(p => p.piece == newPos.piece && p.fen == newPos.fen)) | |
575 | // Start of an infinite loop: exit | |
576 | return false; | |
577 | positions.push(newPos); | |
578 | const rank = (color == 'w' ? 0 : 7); | |
579 | const moves = this.getPotentialMovesFrom(fromSquare); | |
580 | if (moves.some(m => m.end.x == rank && files.includes(m.end.y))) | |
581 | // Found an attack! | |
582 | return true; | |
583 | for (let m of moves) { | |
584 | if (!!m.end.released) { | |
585 | // Turn won't change since !!m.released | |
586 | this.play(m); | |
587 | const res = this.isAttacked_aux( | |
588 | files, color, positions, [m.end.x, m.end.y], m.end.released); | |
589 | this.undo(m); | |
590 | if (res) return true; | |
591 | } | |
592 | } | |
593 | return false; | |
594 | } | |
595 | ||
596 | isAttacked(files, color) { | |
597 | const rank = (color == 'w' ? 0 : 7); | |
598 | // Since it's too difficult (impossible?) to search from the square itself, | |
599 | // let's adopt a suboptimal but working strategy: find all attacks. | |
600 | const c = this.turn; | |
601 | // Artificial turn change is required: | |
602 | this.turn = color; | |
603 | let res = false; | |
604 | outerLoop: for (let i=0; i<8; i++) { | |
605 | for (let j=0; j<8; j++) { | |
606 | // Attacks must start from a normal piece, not an union. | |
607 | // Therefore, the following test is correct. | |
608 | if ( | |
609 | this.board[i][j] != V.EMPTY && | |
610 | [V.KING, V.PAWN, V.ROOK, V.KNIGHT, V.BISHOP, V.QUEEN].includes( | |
611 | this.board[i][j].charAt(1)) && | |
612 | this.board[i][j].charAt(0) == color | |
613 | ) { | |
614 | // Try from here. | |
615 | const moves = this.getPotentialMovesFrom([i, j], "noCastle"); | |
616 | if (moves.some(m => m.end.x == rank && files.includes(m.end.y))) { | |
617 | res = true; | |
618 | break outerLoop; | |
619 | } | |
620 | for (let m of moves) { | |
621 | if (!!m.end.released) { | |
622 | // Turn won't change since !!m.released | |
623 | this.play(m); | |
624 | let positions = []; | |
625 | res = this.isAttacked_aux( | |
626 | files, color, positions, [m.end.x, m.end.y], m.end.released); | |
627 | this.undo(m); | |
628 | if (res) break outerLoop; | |
629 | } | |
630 | } | |
631 | } | |
632 | } | |
633 | } | |
634 | this.turn = c; | |
635 | return res; | |
636 | } | |
637 | ||
638 | // Do not consider checks, except to forbid castling | |
639 | getCheckSquares() { | |
640 | return []; | |
641 | } | |
f3f84707 | 642 | |
9d15c433 | 643 | filterValid(moves) { |
f3f84707 BA |
644 | if (moves.length == 0) return []; |
645 | return moves.filter(m => { | |
646 | if (!m.end.released) return true; | |
647 | // Check for repetitions: | |
648 | V.PlayOnBoard(this.board, m); | |
d2af3400 BA |
649 | const newState = { |
650 | piece: m.end.released, | |
651 | square: { x: m.end.x, y: m.end.y }, | |
652 | position: this.getBaseFen() | |
653 | }; | |
f3f84707 BA |
654 | const repet = |
655 | this.repetitions.some(r => { | |
656 | return ( | |
657 | r.piece == newState.piece && | |
d2af3400 BA |
658 | ( |
659 | r.square.x == newState.square.x && | |
1328e7dd | 660 | r.square.y == newState.square.y |
d2af3400 | 661 | ) && |
f3f84707 BA |
662 | r.position == newState.position |
663 | ); | |
664 | }); | |
665 | V.UndoOnBoard(this.board, m); | |
666 | return !repet; | |
667 | }); | |
9d15c433 BA |
668 | } |
669 | ||
670 | updateCastleFlags(move, piece) { | |
671 | const c = this.turn; | |
672 | const firstRank = (c == "w" ? 7 : 0); | |
673 | if (piece == V.KING && move.appear.length > 0) | |
674 | this.castleFlags[c] = [V.size.y, V.size.y]; | |
675 | else if ( | |
676 | move.start.x == firstRank && | |
677 | this.castleFlags[c].includes(move.start.y) | |
678 | ) { | |
679 | const flagIdx = (move.start.y == this.castleFlags[c][0] ? 0 : 1); | |
680 | this.castleFlags[c][flagIdx] = V.size.y; | |
681 | } | |
682 | else if ( | |
683 | move.end.x == firstRank && | |
684 | this.castleFlags[c].includes(move.end.y) | |
685 | ) { | |
686 | // Move to our rook: necessary normal piece, to union, releasing | |
687 | // (or the rook was moved before!) | |
688 | const flagIdx = (move.end.y == this.castleFlags[c][0] ? 0 : 1); | |
689 | this.castleFlags[c][flagIdx] = V.size.y; | |
690 | } | |
691 | } | |
692 | ||
693 | prePlay(move) { | |
694 | // Easier before move is played in this case (flags are saved) | |
695 | const c = this.turn; | |
696 | const L = this.lastMoveEnd.length; | |
697 | const lm = this.lastMoveEnd[L-1]; | |
8ec71052 BA |
698 | const piece = |
699 | !!lm | |
700 | ? lm.p : | |
701 | this.getPiece(move.vanish[0].x, move.vanish[0].y); | |
9d15c433 BA |
702 | if (piece == V.KING) |
703 | this.kingPos[c] = [move.appear[0].x, move.appear[0].y]; | |
704 | this.updateCastleFlags(move, piece); | |
705 | const pawnFirstRank = (c == 'w' ? 6 : 1); | |
8ec71052 BA |
706 | if ( |
707 | move.start.x == pawnFirstRank && | |
708 | piece == V.PAWN && | |
709 | Math.abs(move.end.x - move.start.x) == 2 | |
710 | ) { | |
711 | // This move turns off a 2-squares pawn flag | |
9d15c433 | 712 | this.pawnFlags[c][move.start.y] = false; |
8ec71052 | 713 | } |
9d15c433 BA |
714 | } |
715 | ||
716 | play(move) { | |
717 | move.flags = JSON.stringify(this.aggregateFlags()); | |
718 | this.prePlay(move); | |
719 | this.epSquares.push(this.getEpSquare(move)); | |
720 | // Check if the move is the last of the turn: all cases except releases | |
721 | if (!move.end.released) { | |
722 | // No more union releases available | |
723 | this.turn = V.GetOppCol(this.turn); | |
724 | this.movesCount++; | |
725 | this.lastMoveEnd.push(null); | |
726 | } | |
727 | else | |
728 | this.lastMoveEnd.push(Object.assign({ p: move.end.released }, move.end)); | |
729 | V.PlayOnBoard(this.board, move); | |
f3f84707 BA |
730 | if (!move.end.released) this.repetitions = []; |
731 | else { | |
732 | this.repetitions.push( | |
733 | { | |
734 | piece: move.end.released, | |
d2af3400 | 735 | square: { x: move.end.x, y: move.end.y }, |
f3f84707 BA |
736 | position: this.getBaseFen() |
737 | } | |
738 | ); | |
739 | } | |
9d15c433 BA |
740 | } |
741 | ||
742 | undo(move) { | |
743 | this.epSquares.pop(); | |
744 | this.disaggregateFlags(JSON.parse(move.flags)); | |
745 | V.UndoOnBoard(this.board, move); | |
746 | this.lastMoveEnd.pop(); | |
747 | if (!move.end.released) { | |
748 | this.turn = V.GetOppCol(this.turn); | |
749 | this.movesCount--; | |
750 | } | |
4573adc5 | 751 | if (!!move.end.released) this.repetitions.pop(); |
9d15c433 BA |
752 | this.postUndo(move); |
753 | } | |
754 | ||
755 | postUndo(move) { | |
756 | if (this.getPiece(move.start.x, move.start.y) == V.KING) | |
757 | this.kingPos[this.turn] = [move.start.x, move.start.y]; | |
758 | } | |
759 | ||
760 | getCurrentScore() { | |
761 | // Check kings: if one is captured, the side lost | |
762 | for (let c of ['w', 'b']) { | |
763 | const kp = this.kingPos[c]; | |
764 | const cell = this.board[kp[0]][kp[1]]; | |
765 | if ( | |
766 | cell[1] != V.KING && | |
767 | ( | |
768 | (c == 'w' && ['a', 'b'].includes(cell[0])) || | |
769 | (c == 'b' && ['v', 'w'].includes(cell[0])) | |
770 | ) | |
771 | ) { | |
772 | // King is captured | |
773 | return (c == 'w' ? "0-1" : "1-0"); | |
774 | } | |
775 | } | |
776 | return "*"; | |
777 | } | |
778 | ||
779 | getComputerMove() { | |
780 | let initMoves = this.getAllValidMoves(); | |
781 | if (initMoves.length == 0) return null; | |
782 | // Loop until valid move is found (no blocked pawn released...) | |
783 | while (true) { | |
784 | let moves = JSON.parse(JSON.stringify(initMoves)); | |
785 | let mvArray = []; | |
786 | let mv = null; | |
787 | // Just play random moves (for now at least. TODO?) | |
788 | while (moves.length > 0) { | |
789 | mv = moves[randInt(moves.length)]; | |
790 | mvArray.push(mv); | |
791 | this.play(mv); | |
792 | if (!!mv.end.released) | |
793 | // A piece was just released from an union | |
794 | moves = this.getPotentialMovesFrom([mv.end.x, mv.end.y]); | |
795 | else break; | |
796 | } | |
797 | for (let i = mvArray.length - 1; i >= 0; i--) this.undo(mvArray[i]); | |
798 | if (!mv.end.released) return (mvArray.length > 1 ? mvArray : mvArray[0]); | |
799 | } | |
2da551a3 | 800 | return null; //never reached |
9d15c433 BA |
801 | } |
802 | ||
803 | // NOTE: evalPosition() is wrong, but unused since bot plays at random | |
804 | ||
805 | getNotation(move) { | |
806 | if (move.appear.length == 2 && move.appear[0].p == V.KING) | |
807 | return (move.end.y < move.start.y ? "0-0-0" : "0-0"); | |
808 | ||
809 | const c = this.turn; | |
810 | const L = this.lastMoveEnd.length; | |
811 | const lm = this.lastMoveEnd[L-1]; | |
812 | let piece = null; | |
813 | if (!lm && move.vanish.length == 0) | |
814 | // When importing a game, the info move.released is lost | |
815 | piece = move.appear[0].p; | |
816 | else piece = (!!lm ? lm.p : move.vanish[0].p); | |
817 | if (!(ChessRules.PIECES.includes(piece))) { | |
818 | // Decode (moving) union | |
819 | const up = this.getUnionPieces( | |
820 | move.vanish.length > 0 ? move.vanish[0].c : move.appear[0].c, piece); | |
821 | piece = up[c] | |
822 | } | |
823 | ||
824 | // Basic move notation: | |
825 | let notation = piece.toUpperCase(); | |
826 | if ( | |
827 | this.board[move.end.x][move.end.y] != V.EMPTY || | |
828 | (piece == V.PAWN && move.start.y != move.end.y) | |
829 | ) { | |
830 | notation += "x"; | |
831 | } | |
832 | const finalSquare = V.CoordsToSquare(move.end); | |
833 | notation += finalSquare; | |
834 | ||
835 | // Add potential promotion indications: | |
836 | const firstLastRank = (c == 'w' ? [7, 0] : [0, 7]); | |
837 | if (move.end.x == firstLastRank[1] && piece == V.PAWN) { | |
afcfb852 BA |
838 | notation += "="; |
839 | if (ChessRules.PIECES.includes(move.appear[0].p)) | |
840 | notation += move.appear[0].p.toUpperCase(); | |
841 | else { | |
842 | const up = this.getUnionPieces(move.appear[0].c, move.appear[0].p); | |
843 | notation += up[c].toUpperCase(); | |
844 | } | |
9d15c433 BA |
845 | } |
846 | else if ( | |
847 | move.end.x == firstLastRank[0] && | |
848 | move.vanish.length > 0 && | |
849 | ['c', 'd', 'e', 'f', 'g'].includes(move.vanish[0].p) | |
850 | ) { | |
851 | // We promoted an opponent's pawn | |
852 | const oppCol = V.GetOppCol(c); | |
853 | const up = this.getUnionPieces(move.appear[0].c, move.appear[0].p); | |
854 | notation += "=" + up[oppCol].toUpperCase(); | |
855 | } | |
856 | ||
857 | return notation; | |
858 | } | |
859 | ||
860 | }; |