Add falling pawn mode for Recycle + fix animation bug
[xogo.git] / base_rules.js
CommitLineData
41534b92
BA
1import { Random } from "/utils/alea.js";
2import { ArrayFun } from "/utils/array.js";
3import PiPo from "/utils/PiPo.js";
4import Move from "/utils/Move.js";
5
6// NOTE: x coords: top to bottom (white perspective); y: left to right
cc2c7183 7// NOTE: ChessRules is aliased as window.C, and variants as window.V
41534b92
BA
8export default class ChessRules {
9
10 /////////////////////////
11 // VARIANT SPECIFICATIONS
12
13 // Some variants have specific options, like the number of pawns in Monster,
14 // or the board size for Pandemonium.
15 // Users can generally select a randomness level from 0 to 2.
16 static get Options() {
17 return {
18 // NOTE: some options are required for FEN generation, some aren't.
19 select: [{
20 label: "Randomness",
21 variable: "randomness",
22 defaut: 0,
23 options: [
24 { label: "Deterministic", value: 0 },
25 { label: "Symmetric random", value: 1 },
26 { label: "Asymmetric random", value: 2 }
27 ]
28 }],
f8b43ef7
BA
29 check: [
30 {
31 label: "Capture king",
32 defaut: false,
33 variable: "taking"
34 },
35 {
36 label: "Falling pawn",
37 defaut: false,
38 variable: "pawnfall"
39 }
40 ],
41534b92
BA
41 // Game modifiers (using "elementary variants"). Default: false
42 styles: [
43 "atomic",
44 "balance", //takes precedence over doublemove & progressive
45 "cannibal",
46 "capture",
47 "crazyhouse",
48 "cylinder", //ok with all
49 "dark",
50 "doublemove",
51 "madrasi",
52 "progressive", //(natural) priority over doublemove
53 "recycle",
54 "rifle",
55 "teleport",
56 "zen"
57 ]
58 };
59 }
60
61 // Pawns specifications
62 get pawnSpecs() {
63 return {
64 directions: { 'w': -1, 'b': 1 },
65 initShift: { w: 1, b: 1 },
66 twoSquares: true,
67 threeSquares: false,
68 canCapture: true,
69 captureBackward: false,
70 bidirectional: false,
71 promotions: ['r', 'n', 'b', 'q']
72 };
73 }
74
75 // Some variants don't have flags:
76 get hasFlags() {
77 return true;
78 }
79 // Or castle
80 get hasCastle() {
81 return this.hasFlags;
82 }
83
84 // En-passant captures allowed?
85 get hasEnpassant() {
86 return true;
87 }
88
89 get hasReserve() {
90 return (
91 !!this.options["crazyhouse"] ||
92 (!!this.options["recycle"] && !this.options["teleport"])
93 );
94 }
95
96 get noAnimate() {
97 return !!this.options["dark"];
98 }
99
100 // Some variants use click infos:
101 doClick([x, y]) {
102 if (typeof x != "number") return null; //click on reserves
103 if (
cc2c7183 104 this.options["teleport"] && this.subTurnTeleport == 2 &&
41534b92
BA
105 this.board[x][y] == ""
106 ) {
107 return new Move({
108 start: {x: this.captured.x, y: this.captured.y},
109 appear: [
110 new PiPo({
111 x: x,
112 y: y,
113 c: this.captured.c, //this.turn,
114 p: this.captured.p
115 })
116 ],
117 vanish: []
118 });
119 }
120 return null;
121 }
122
123 ////////////////////
124 // COORDINATES UTILS
125
126 // 3 --> d (column number to letter)
127 static CoordToColumn(colnum) {
128 return String.fromCharCode(97 + colnum);
129 }
130
131 // d --> 3 (column letter to number)
132 static ColumnToCoord(columnStr) {
133 return columnStr.charCodeAt(0) - 97;
134 }
135
136 // 7 (numeric) --> 1 (str) [from black viewpoint].
137 static CoordToRow(rownum) {
138 return rownum;
139 }
140
141 // NOTE: wrong row index (1 should be 7 ...etc). But OK for the usage.
142 static RowToCoord(rownumStr) {
143 // NOTE: 30 is way more than enough (allow up to 29 rows on one character)
144 return parseInt(rownumStr, 30);
145 }
146
147 // a2 --> {x:2,y:0} (this is in fact a6)
148 static SquareToCoords(sq) {
149 return {
cc2c7183 150 x: C.RowToCoord(sq[1]),
41534b92 151 // NOTE: column is always one char => max 26 columns
cc2c7183 152 y: C.ColumnToCoord(sq[0])
41534b92
BA
153 };
154 }
155
156 // {x:0,y:4} --> e0 (should be e8)
157 static CoordsToSquare(coords) {
cc2c7183 158 return C.CoordToColumn(coords.y) + C.CoordToRow(coords.x);
41534b92
BA
159 }
160
161 coordsToId([x, y]) {
162 if (typeof x == "number")
163 return `${this.containerId}|sq-${x.toString(30)}-${y.toString(30)}`;
164 // Reserve :
165 return `${this.containerId}|rsq-${x}-${y}`;
166 }
167
168 idToCoords(targetId) {
169 if (!targetId) return null; //outside page, maybe...
170 const idParts = targetId.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
171 if (
172 idParts.length < 2 ||
173 idParts[0] != this.containerId ||
174 !idParts[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
175 ) {
176 return null;
177 }
178 const squares = idParts[1].split('-');
179 if (squares[0] == "sq")
180 return [ parseInt(squares[1], 30), parseInt(squares[2], 30) ];
181 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters)
182 return [squares[1], squares[2]];
183 }
184
185 /////////////
186 // FEN UTILS
187
188 // Turn "wb" into "B" (for FEN)
189 board2fen(b) {
190 return b[0] == "w" ? b[1].toUpperCase() : b[1];
191 }
192
193 // Turn "p" into "bp" (for board)
194 fen2board(f) {
195 return f.charCodeAt(0) <= 90 ? "w" + f.toLowerCase() : "b" + f;
196 }
197
198 // Setup the initial random-or-not (asymmetric-or-not) position
199 genRandInitFen(seed) {
200 Random.setSeed(seed);
201
202 let fen, flags = "0707";
cc2c7183 203 if (!this.options.randomness)
41534b92
BA
204 // Deterministic:
205 fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
206
207 else {
208 // Randomize
209 let pieces = { w: new Array(8), b: new Array(8) };
210 flags = "";
211 // Shuffle pieces on first (and last rank if randomness == 2)
212 for (let c of ["w", "b"]) {
213 if (c == 'b' && this.options.randomness == 1) {
214 pieces['b'] = pieces['w'];
215 flags += flags;
216 break;
217 }
218
219 let positions = ArrayFun.range(8);
220
221 // Get random squares for bishops
222 let randIndex = 2 * Random.randInt(4);
223 const bishop1Pos = positions[randIndex];
224 // The second bishop must be on a square of different color
225 let randIndex_tmp = 2 * Random.randInt(4) + 1;
226 const bishop2Pos = positions[randIndex_tmp];
227 // Remove chosen squares
228 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
229 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
230
231 // Get random squares for knights
232 randIndex = Random.randInt(6);
233 const knight1Pos = positions[randIndex];
234 positions.splice(randIndex, 1);
235 randIndex = Random.randInt(5);
236 const knight2Pos = positions[randIndex];
237 positions.splice(randIndex, 1);
238
239 // Get random square for queen
240 randIndex = Random.randInt(4);
241 const queenPos = positions[randIndex];
242 positions.splice(randIndex, 1);
243
244 // Rooks and king positions are now fixed,
245 // because of the ordering rook-king-rook
246 const rook1Pos = positions[0];
247 const kingPos = positions[1];
248 const rook2Pos = positions[2];
249
250 // Finally put the shuffled pieces in the board array
251 pieces[c][rook1Pos] = "r";
252 pieces[c][knight1Pos] = "n";
253 pieces[c][bishop1Pos] = "b";
254 pieces[c][queenPos] = "q";
255 pieces[c][kingPos] = "k";
256 pieces[c][bishop2Pos] = "b";
257 pieces[c][knight2Pos] = "n";
258 pieces[c][rook2Pos] = "r";
259 flags += rook1Pos.toString() + rook2Pos.toString();
260 }
261 fen = (
262 pieces["b"].join("") +
263 "/pppppppp/8/8/8/8/PPPPPPPP/" +
264 pieces["w"].join("").toUpperCase() +
265 " w 0"
266 );
267 }
268 // Add turn + flags + enpassant (+ reserve)
269 let parts = [];
270 if (this.hasFlags) parts.push(`"flags":"${flags}"`);
271 if (this.hasEnpassant) parts.push('"enpassant":"-"');
272 if (this.hasReserve) parts.push('"reserve":"000000000000"');
273 if (this.options["crazyhouse"]) parts.push('"ispawn":"-"');
274 if (parts.length >= 1) fen += " {" + parts.join(",") + "}";
275 return fen;
276 }
277
278 // "Parse" FEN: just return untransformed string data
279 parseFen(fen) {
280 const fenParts = fen.split(" ");
281 let res = {
282 position: fenParts[0],
283 turn: fenParts[1],
284 movesCount: fenParts[2]
285 };
286 if (fenParts.length > 3) res = Object.assign(res, JSON.parse(fenParts[3]));
287 return res;
288 }
289
290 // Return current fen (game state)
291 getFen() {
292 let fen = (
293 this.getBaseFen() + " " +
294 this.getTurnFen() + " " +
295 this.movesCount
296 );
297 let parts = [];
298 if (this.hasFlags) parts.push(`"flags":"${this.getFlagsFen()}"`);
299 if (this.hasEnpassant)
300 parts.push(`"enpassant":"${this.getEnpassantFen()}"`);
301 if (this.hasReserve) parts.push(`"reserve":"${this.getReserveFen()}"`);
302 if (this.options["crazyhouse"])
303 parts.push(`"ispawn":"${this.getIspawnFen()}"`);
304 if (parts.length >= 1) fen += " {" + parts.join(",") + "}";
305 return fen;
306 }
307
308 // Position part of the FEN string
309 getBaseFen() {
310 const format = (count) => {
311 // if more than 9 consecutive free spaces, break the integer,
312 // otherwise FEN parsing will fail.
313 if (count <= 9) return count;
314 // Most boards of size < 18:
315 if (count <= 18) return "9" + (count - 9);
316 // Except Gomoku:
317 return "99" + (count - 18);
318 };
319 let position = "";
320 for (let i = 0; i < this.size.y; i++) {
321 let emptyCount = 0;
322 for (let j = 0; j < this.size.x; j++) {
323 if (this.board[i][j] == "") emptyCount++;
324 else {
325 if (emptyCount > 0) {
326 // Add empty squares in-between
327 position += format(emptyCount);
328 emptyCount = 0;
329 }
330 position += this.board2fen(this.board[i][j]);
331 }
332 }
333 if (emptyCount > 0)
334 // "Flush remainder"
335 position += format(emptyCount);
336 if (i < this.size.y - 1) position += "/"; //separate rows
337 }
338 return position;
339 }
340
341 getTurnFen() {
342 return this.turn;
343 }
344
345 // Flags part of the FEN string
346 getFlagsFen() {
347 return ["w", "b"].map(c => {
348 return this.castleFlags[c].map(x => x.toString(30)).join("");
349 }).join("");
350 }
351
352 // Enpassant part of the FEN string
353 getEnpassantFen() {
354 if (!this.epSquare) return "-"; //no en-passant
cc2c7183 355 return C.CoordsToSquare(this.epSquare);
41534b92
BA
356 }
357
358 getReserveFen() {
359 return (
360 ["w","b"].map(c => Object.values(this.reserve[c]).join("")).join("")
361 );
362 }
363
364 getIspawnFen() {
365 const coords = Object.keys(this.ispawn);
366 if (coords.length == 0) return "-";
cc2c7183 367 return coords.map(C.CoordsToSquare).join(",");
41534b92
BA
368 }
369
370 // Set flags from fen (castle: white a,h then black a,h)
371 setFlags(fenflags) {
372 this.castleFlags = {
373 w: [0, 1].map(i => parseInt(fenflags.charAt(i), 30)),
374 b: [2, 3].map(i => parseInt(fenflags.charAt(i), 30))
375 };
376 }
377
378 //////////////////
379 // INITIALIZATION
380
381 // Fen string fully describes the game state
382 constructor(o) {
cc2c7183
BA
383 window.C = ChessRules; //easier alias
384
41534b92
BA
385 this.options = o.options;
386 this.playerColor = o.color;
387 this.afterPlay = o.afterPlay;
388
389 // FEN-related:
390 if (!o.fen) o.fen = this.genRandInitFen(o.seed);
391 const fenParsed = this.parseFen(o.fen);
392 this.board = this.getBoard(fenParsed.position);
393 this.turn = fenParsed.turn;
394 this.movesCount = parseInt(fenParsed.movesCount, 10);
395 this.setOtherVariables(fenParsed);
396
397 // Graphical (can use variables defined above)
398 this.containerId = o.element;
399 this.graphicalInit();
400 }
401
402 // Turn position fen into double array ["wb","wp","bk",...]
403 getBoard(position) {
404 const rows = position.split("/");
405 let board = ArrayFun.init(this.size.x, this.size.y, "");
406 for (let i = 0; i < rows.length; i++) {
407 let j = 0;
408 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) {
409 const character = rows[i][indexInRow];
410 const num = parseInt(character, 10);
411 // If num is a number, just shift j:
412 if (!isNaN(num)) j += num;
413 // Else: something at position i,j
414 else board[i][j++] = this.fen2board(character);
415 }
416 }
417 return board;
418 }
419
420 // Some additional variables from FEN (variant dependant)
421 setOtherVariables(fenParsed) {
422 // Set flags and enpassant:
423 if (this.hasFlags) this.setFlags(fenParsed.flags);
424 if (this.hasEnpassant)
425 this.epSquare = this.getEpSquare(fenParsed.enpassant);
426 if (this.hasReserve) this.initReserves(fenParsed.reserve);
427 if (this.options["crazyhouse"]) this.initIspawn(fenParsed.ispawn);
428 this.subTurn = 1; //may be unused
cc2c7183
BA
429 if (this.options["teleport"]) {
430 this.subTurnTeleport = 1;
431 this.captured = null;
432 }
41534b92
BA
433 if (this.options["dark"]) {
434 this.enlightened = ArrayFun.init(this.size.x, this.size.y);
435 // Setup enlightened: squares reachable by player side
436 this.updateEnlightened(false);
437 }
438 }
439
440 updateEnlightened(withGraphics) {
441 let newEnlightened = ArrayFun.init(this.size.x, this.size.y, false);
442 const pawnShift = { w: -1, b: 1 };
443 // Add pieces positions + all squares reachable by moves (includes Zen):
444 // (watch out special pawns case)
445 for (let x=0; x<this.size.x; x++) {
446 for (let y=0; y<this.size.y; y++) {
447 if (this.board[x][y] != "" && this.getColor(x, y) == this.playerColor)
448 {
449 newEnlightened[x][y] = true;
cc2c7183 450 if (this.getPiece(x, y) == "p") {
41534b92 451 // Attacking squares wouldn't be highlighted if no captures:
cc2c7183 452 this.pieces(this.playerColor)["p"].attack.forEach(step => {
41534b92
BA
453 const [i, j] = [x + step[0], this.computeY(y + step[1])];
454 if (this.onBoard(i, j) && this.board[i][j] == "")
455 newEnlightened[i][j] = true;
456 });
457 }
458 this.getPotentialMovesFrom([x, y]).forEach(m => {
459 newEnlightened[m.end.x][m.end.y] = true;
460 });
461 }
462 }
463 }
464 if (this.epSquare) this.enlightEnpassant(newEnlightened);
465 if (withGraphics) this.graphUpdateEnlightened(newEnlightened);
466 this.enlightened = newEnlightened;
467 }
468
469 // Include en-passant capturing square if any:
470 enlightEnpassant(newEnlightened) {
cc2c7183 471 const steps = this.pieces(this.playerColor)["p"].attack;
41534b92
BA
472 for (let step of steps) {
473 const x = this.epSquare.x - step[0],
474 y = this.computeY(this.epSquare.y - step[1]);
475 if (
476 this.onBoard(x, y) &&
477 this.getColor(x, y) == this.playerColor &&
cc2c7183 478 this.getPieceType(x, y) == "p"
41534b92
BA
479 ) {
480 newEnlightened[x][this.epSquare.y] = true;
481 break;
482 }
483 }
484 }
485
486 // Apply diff this.enlightened --> newEnlightened on board
487 graphUpdateEnlightened(newEnlightened) {
488 let container = document.getElementById(this.containerId);
489 const r = container.getBoundingClientRect();
490 const pieceWidth = this.getPieceWidth(r.width);
491 for (let x=0; x<this.size.x; x++) {
492 for (let y=0; y<this.size.y; y++) {
493 if (this.enlightened[x][y] && !newEnlightened[x][y]) {
494 let elt = document.getElementById(this.coordsToId([x, y]));
2dba3fe1 495 elt.classList.add("in-shadow");
41534b92
BA
496 if (this.g_pieces[x][y]) {
497 this.g_pieces[x][y].remove();
498 this.g_pieces[x][y] = null;
499 }
500 }
501 else if (!this.enlightened[x][y] && newEnlightened[x][y]) {
502 let elt = document.getElementById(this.coordsToId([x, y]));
2dba3fe1 503 elt.classList.remove("in-shadow");
41534b92 504 if (this.board[x][y] != "") {
e5cea9ca
BA
505 const color = this.getColor(x, y);
506 const piece = this.getPiece(x, y);
41534b92
BA
507 this.g_pieces[x][y] = document.createElement("piece");
508 let newClasses = [
509 this.pieces()[piece]["class"],
510 color == "w" ? "white" : "black"
511 ];
512 newClasses.forEach(cl => this.g_pieces[x][y].classList.add(cl));
513 this.g_pieces[x][y].style.width = pieceWidth + "px";
514 this.g_pieces[x][y].style.height = pieceWidth + "px";
515 const [ip, jp] = this.getPixelPosition(x, y, r);
516 this.g_pieces[x][y].style.transform =
517 `translate(${ip}px,${jp}px)`;
518 container.appendChild(this.g_pieces[x][y]);
519 }
520 }
521 }
522 }
523 }
524
525 // ordering p,r,n,b,q,k (most general + count in base 30 if needed)
526 initReserves(reserveStr) {
527 const counts = reserveStr.split("").map(c => parseInt(c, 30));
528 this.reserve = { w: {}, b: {} };
529 const pieceName = Object.keys(this.pieces());
530 for (let i of ArrayFun.range(12)) {
531 if (i < 6) this.reserve['w'][pieceName[i]] = counts[i];
532 else this.reserve['b'][pieceName[i-6]] = counts[i];
533 }
534 }
535
536 initIspawn(ispawnStr) {
537 if (ispawnStr != "-") {
cc2c7183 538 this.ispawn = ispawnStr.split(",").map(C.SquareToCoords)
41534b92
BA
539 .reduce((o, key) => ({ ...o, [key]: true}), {});
540 }
541 else this.ispawn = {};
542 }
543
544 getNbReservePieces(color) {
545 return (
546 Object.values(this.reserve[color]).reduce(
547 (oldV,newV) => oldV + (newV > 0 ? 1 : 0), 0)
548 );
549 }
550
551 //////////////
552 // VISUAL PART
553
554 getPieceWidth(rwidth) {
555 return (rwidth / this.size.y);
556 }
557
558 getSquareWidth(rwidth) {
559 return this.getPieceWidth(rwidth);
560 }
561
562 getReserveSquareSize(rwidth, nbR) {
563 const sqSize = this.getSquareWidth(rwidth);
564 return Math.min(sqSize, rwidth / nbR);
565 }
566
567 getReserveNumId(color, piece) {
568 return `${this.containerId}|rnum-${color}${piece}`;
569 }
570
571 graphicalInit() {
572 // NOTE: not window.onresize = this.re_drawBoardElts because scope (this)
573 window.onresize = () => this.re_drawBoardElements();
574 this.re_drawBoardElements();
575 this.initMouseEvents();
576 const container = document.getElementById(this.containerId);
577 new ResizeObserver(this.rescale).observe(container);
578 }
579
580 re_drawBoardElements() {
581 const board = this.getSvgChessboard();
cc2c7183 582 const oppCol = C.GetOppCol(this.playerColor);
41534b92
BA
583 let container = document.getElementById(this.containerId);
584 container.innerHTML = "";
585 container.insertAdjacentHTML('beforeend', board);
586 let cb = container.querySelector("#" + this.containerId + "_SVG");
587 const aspectRatio = this.size.y / this.size.x;
588 // Compare window ratio width / height to aspectRatio:
589 const windowRatio = window.innerWidth / window.innerHeight;
590 let cbWidth, cbHeight;
591 if (windowRatio <= aspectRatio) {
592 // Limiting dimension is width:
593 cbWidth = Math.min(window.innerWidth, 767);
594 cbHeight = cbWidth / aspectRatio;
595 }
596 else {
597 // Limiting dimension is height:
598 cbHeight = Math.min(window.innerHeight, 767);
599 cbWidth = cbHeight * aspectRatio;
600 }
601 if (this.reserve) {
602 const sqSize = cbWidth / this.size.y;
603 // NOTE: allocate space for reserves (up/down) even if they are empty
604 if ((window.innerHeight - cbHeight) / 2 < sqSize + 5) {
605 cbHeight = window.innerHeight - 2 * (sqSize + 5);
606 cbWidth = cbHeight * aspectRatio;
607 }
608 }
609 container.style.width = cbWidth + "px";
610 container.style.height = cbHeight + "px";
611 // Center chessboard:
612 const spaceLeft = (window.innerWidth - cbWidth) / 2,
613 spaceTop = (window.innerHeight - cbHeight) / 2;
614 container.style.left = spaceLeft + "px";
615 container.style.top = spaceTop + "px";
616 // Give sizes instead of recomputing them,
617 // because chessboard might not be drawn yet.
618 this.setupPieces({
619 width: cbWidth,
620 height: cbHeight,
621 x: spaceLeft,
622 y: spaceTop
623 });
624 }
625
626 // Get SVG board (background, no pieces)
627 getSvgChessboard() {
628 const [sizeX, sizeY] = [this.size.x, this.size.y];
629 const flipped = (this.playerColor == 'b');
630 let board = `
631 <svg
632 viewBox="0 0 80 80"
633 version="1.1"
634 id="${this.containerId}_SVG">
635 <g>`;
636 for (let i=0; i < sizeX; i++) {
637 for (let j=0; j < sizeY; j++) {
638 const ii = (flipped ? this.size.x - 1 - i : i);
639 const jj = (flipped ? this.size.y - 1 - j : j);
c7bf7b1b
BA
640 let classes = this.getSquareColorClass(ii, jj);
641 if (this.enlightened && !this.enlightened[ii][jj])
642 classes += " in-shadow";
41534b92 643 // NOTE: x / y reversed because coordinates system is reversed.
c7bf7b1b
BA
644 board += `<rect
645 class="${classes}"
41534b92
BA
646 id="${this.coordsToId([ii, jj])}"
647 width="10"
648 height="10"
649 x="${10*j}"
650 y="${10*i}" />`;
651 }
652 }
653 board += "</g></svg>";
654 return board;
655 }
656
cc2c7183 657 // Generally light square bottom-right
c7bf7b1b
BA
658 getSquareColorClass(i, j) {
659 return ((i+j) % 2 == 0 ? "light-square": "dark-square");
41534b92
BA
660 }
661
662 setupPieces(r) {
663 if (this.g_pieces) {
664 // Refreshing: delete old pieces first
665 for (let i=0; i<this.size.x; i++) {
666 for (let j=0; j<this.size.y; j++) {
667 if (this.g_pieces[i][j]) {
668 this.g_pieces[i][j].remove();
669 this.g_pieces[i][j] = null;
670 }
671 }
672 }
673 }
674 else this.g_pieces = ArrayFun.init(this.size.x, this.size.y, null);
675 let container = document.getElementById(this.containerId);
21e8e712 676 if (!r) r = container.getBoundingClientRect();
41534b92
BA
677 const pieceWidth = this.getPieceWidth(r.width);
678 for (let i=0; i < this.size.x; i++) {
679 for (let j=0; j < this.size.y; j++) {
680 if (
681 this.board[i][j] != "" &&
682 (!this.options["dark"] || this.enlightened[i][j])
683 ) {
41534b92 684 const color = this.getColor(i, j);
cc2c7183 685 const piece = this.getPiece(i, j);
41534b92
BA
686 this.g_pieces[i][j] = document.createElement("piece");
687 this.g_pieces[i][j].classList.add(this.pieces()[piece]["class"]);
688 this.g_pieces[i][j].classList.add(color == "w" ? "white" : "black");
689 this.g_pieces[i][j].style.width = pieceWidth + "px";
690 this.g_pieces[i][j].style.height = pieceWidth + "px";
691 const [ip, jp] = this.getPixelPosition(i, j, r);
692 this.g_pieces[i][j].style.transform = `translate(${ip}px,${jp}px)`;
693 container.appendChild(this.g_pieces[i][j]);
694 }
695 }
696 }
697 if (this.reserve) this.re_drawReserve(['w', 'b'], r);
698 }
699
700 // NOTE: assume !!this.reserve
701 re_drawReserve(colors, r) {
702 if (this.r_pieces) {
703 // Remove (old) reserve pieces
704 for (let c of colors) {
705 if (!this.reserve[c]) continue;
706 Object.keys(this.reserve[c]).forEach(p => {
707 if (this.r_pieces[c][p]) {
708 this.r_pieces[c][p].remove();
709 delete this.r_pieces[c][p];
710 const numId = this.getReserveNumId(c, p);
711 document.getElementById(numId).remove();
712 }
713 });
714 let reservesDiv = document.getElementById("reserves_" + c);
715 if (reservesDiv) reservesDiv.remove();
716 }
717 }
718 else this.r_pieces = { 'w': {}, 'b': {} };
719 if (!r) {
720 const container = document.getElementById(this.containerId);
721 r = container.getBoundingClientRect();
722 }
41534b92
BA
723 for (let c of colors) {
724 if (!this.reserve[c]) continue;
725 const nbR = this.getNbReservePieces(c);
726 if (nbR == 0) continue;
727 const sqResSize = this.getReserveSquareSize(r.width, nbR);
728 let ridx = 0;
729 const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5);
730 const [i0, j0] = [r.x, r.y + vShift];
731 let rcontainer = document.createElement("div");
732 rcontainer.id = "reserves_" + c;
733 rcontainer.classList.add("reserves");
734 rcontainer.style.left = i0 + "px";
735 rcontainer.style.top = j0 + "px";
1aa9054d
BA
736 // NOTE: +1 fix display bug on Firefox at least
737 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
41534b92
BA
738 rcontainer.style.height = sqResSize + "px";
739 document.getElementById("boardContainer").appendChild(rcontainer);
740 for (let p of Object.keys(this.reserve[c])) {
741 if (this.reserve[c][p] == 0) continue;
742 let r_cell = document.createElement("div");
743 r_cell.id = this.coordsToId([c, p]);
744 r_cell.classList.add("reserve-cell");
1aa9054d
BA
745 r_cell.style.width = sqResSize + "px";
746 r_cell.style.height = sqResSize + "px";
41534b92
BA
747 rcontainer.appendChild(r_cell);
748 let piece = document.createElement("piece");
749 const pieceSpec = this.pieces(c)[p];
750 piece.classList.add(pieceSpec["class"]);
751 piece.classList.add(c == 'w' ? "white" : "black");
752 piece.style.width = "100%";
753 piece.style.height = "100%";
754 this.r_pieces[c][p] = piece;
755 r_cell.appendChild(piece);
756 let number = document.createElement("div");
757 number.textContent = this.reserve[c][p];
758 number.classList.add("reserve-num");
759 number.id = this.getReserveNumId(c, p);
760 const fontSize = "1.3em";
761 number.style.fontSize = fontSize;
762 number.style.fontSize = fontSize;
763 r_cell.appendChild(number);
764 ridx++;
765 }
766 }
767 }
768
769 updateReserve(color, piece, count) {
55a15dcb 770 if (this.options["cannibal"] && C.CannibalKings[piece])
cc2c7183 771 piece = "k"; //capturing cannibal king: back to king form
41534b92
BA
772 const oldCount = this.reserve[color][piece];
773 this.reserve[color][piece] = count;
774 // Redrawing is much easier if count==0
775 if ([oldCount, count].includes(0)) this.re_drawReserve([color]);
776 else {
777 const numId = this.getReserveNumId(color, piece);
778 document.getElementById(numId).textContent = count;
779 }
780 }
781
782 // After resize event: no need to destroy/recreate pieces
783 rescale() {
784 let container = document.getElementById(this.containerId);
785 if (!container) return; //useful at initial loading
786 const r = container.getBoundingClientRect();
787 const newRatio = r.width / r.height;
788 const aspectRatio = this.size.y / this.size.x;
789 let newWidth = r.width,
790 newHeight = r.height;
791 if (newRatio > aspectRatio) {
792 newWidth = r.height * aspectRatio;
793 container.style.width = newWidth + "px";
794 }
795 else if (newRatio < aspectRatio) {
796 newHeight = r.width / aspectRatio;
797 container.style.height = newHeight + "px";
798 }
799 const newX = (window.innerWidth - newWidth) / 2;
800 container.style.left = newX + "px";
801 const newY = (window.innerHeight - newHeight) / 2;
802 container.style.top = newY + "px";
803 const newR = { x: newX, y: newY, width: newWidth, height: newHeight };
804 const pieceWidth = this.getPieceWidth(newWidth);
805 for (let i=0; i < this.size.x; i++) {
806 for (let j=0; j < this.size.y; j++) {
807 if (this.board[i][j] != "") {
808 // NOTE: could also use CSS transform "scale"
809 this.g_pieces[i][j].style.width = pieceWidth + "px";
810 this.g_pieces[i][j].style.height = pieceWidth + "px";
811 const [ip, jp] = this.getPixelPosition(i, j, newR);
812 this.g_pieces[i][j].style.transform = `translate(${ip}px,${jp}px)`;
813 }
814 }
815 }
816 if (this.reserve) this.rescaleReserve(newR);
817 }
818
819 rescaleReserve(r) {
41534b92
BA
820 for (let c of ['w','b']) {
821 if (!this.reserve[c]) continue;
822 const nbR = this.getNbReservePieces(c);
823 if (nbR == 0) continue;
824 // Resize container first
825 const sqResSize = this.getReserveSquareSize(r.width, nbR);
826 const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5);
827 const [i0, j0] = [r.x, r.y + vShift];
828 let rcontainer = document.getElementById("reserves_" + c);
829 rcontainer.style.left = i0 + "px";
830 rcontainer.style.top = j0 + "px";
1aa9054d 831 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
41534b92
BA
832 rcontainer.style.height = sqResSize + "px";
833 // And then reserve cells:
834 const rpieceWidth = this.getReserveSquareSize(r.width, nbR);
835 Object.keys(this.reserve[c]).forEach(p => {
836 if (this.reserve[c][p] == 0) return;
837 let r_cell = document.getElementById(this.coordsToId([c, p]));
1aa9054d
BA
838 r_cell.style.width = sqResSize + "px";
839 r_cell.style.height = sqResSize + "px";
41534b92
BA
840 });
841 }
842 }
843
844 // Return the absolute pixel coordinates given current position.
845 // Our coordinate system differs from CSS one (x <--> y).
846 // We return here the CSS coordinates (more useful).
847 getPixelPosition(i, j, r) {
848 const sqSize = this.getSquareWidth(r.width);
849 if (i < 0 || j < 0) return [0, 0]; //piece vanishes
850 const flipped = (this.playerColor == 'b');
851 const x = (flipped ? this.size.y - 1 - j : j) * sqSize;
852 const y = (flipped ? this.size.x - 1 - i : i) * sqSize;
853 return [x, y];
854 }
855
856 initMouseEvents() {
857 let container = document.getElementById(this.containerId);
858
859 const getOffset = e => {
860 if (e.clientX) return {x: e.clientX, y: e.clientY}; //Mouse
861 let touchLocation = null;
862 if (e.targetTouches && e.targetTouches.length >= 1)
863 // Touch screen, dragstart
864 touchLocation = e.targetTouches[0];
865 else if (e.changedTouches && e.changedTouches.length >= 1)
866 // Touch screen, dragend
867 touchLocation = e.changedTouches[0];
868 if (touchLocation)
11625344 869 return {x: touchLocation.clientX, y: touchLocation.clientY};
41534b92
BA
870 return [0, 0]; //Big trouble here =)
871 }
872
873 const centerOnCursor = (piece, e) => {
874 const centerShift = sqSize / 2;
875 const offset = getOffset(e);
876 piece.style.left = (offset.x - centerShift) + "px";
877 piece.style.top = (offset.y - centerShift) + "px";
878 }
879
880 let start = null,
881 r = null,
882 startPiece, curPiece = null,
883 sqSize;
884 const mousedown = (e) => {
cb17fed8
BA
885 // Disable zoom on smartphones:
886 if (e.touches && e.touches.length > 1) e.preventDefault();
41534b92
BA
887 r = container.getBoundingClientRect();
888 sqSize = this.getSquareWidth(r.width);
889 const square = this.idToCoords(e.target.id);
890 if (square) {
891 const [i, j] = square;
892 const move = this.doClick([i, j]);
893 if (move) this.playPlusVisual(move);
894 else {
895 if (typeof i != "number") startPiece = this.r_pieces[i][j];
896 else if (this.g_pieces[i][j]) startPiece = this.g_pieces[i][j];
897 if (startPiece && this.canIplay(i, j)) {
898 e.preventDefault();
899 start = { x: i, y: j };
900 curPiece = startPiece.cloneNode();
901 curPiece.style.transform = "none";
902 curPiece.style.zIndex = 5;
903 curPiece.style.width = sqSize + "px";
904 curPiece.style.height = sqSize + "px";
905 centerOnCursor(curPiece, e);
906 document.getElementById("boardContainer").appendChild(curPiece);
907 startPiece.style.opacity = "0.4";
908 container.style.cursor = "none";
909 }
910 }
911 }
912 };
913
914 const mousemove = (e) => {
915 if (start) {
916 e.preventDefault();
917 centerOnCursor(curPiece, e);
918 }
11625344
BA
919 else if (e.changedTouches && e.changedTouches.length >= 1)
920 // Attempt to prevent horizontal swipe...
921 e.preventDefault();
41534b92
BA
922 };
923
924 const mouseup = (e) => {
925 const newR = container.getBoundingClientRect();
926 if (newR.width != r.width || newR.height != r.height) {
927 this.rescale();
928 return;
929 }
930 if (!start) return;
931 const [x, y] = [start.x, start.y];
932 start = null;
933 e.preventDefault();
934 container.style.cursor = "pointer";
935 startPiece.style.opacity = "1";
936 const offset = getOffset(e);
937 const landingElt = document.elementFromPoint(offset.x, offset.y);
938 const sq = this.idToCoords(landingElt.id);
939 if (sq) {
940 const [i, j] = sq;
941 // NOTE: clearly suboptimal, but much easier, and not a big deal.
942 const potentialMoves = this.getPotentialMovesFrom([x, y])
943 .filter(m => m.end.x == i && m.end.y == j);
944 const moves = this.filterValid(potentialMoves);
945 if (moves.length >= 2) this.showChoices(moves, r);
946 else if (moves.length == 1) this.playPlusVisual(moves[0], r);
947 }
948 curPiece.remove();
949 };
950
951 if ('onmousedown' in window) {
952 document.addEventListener("mousedown", mousedown);
953 document.addEventListener("mousemove", mousemove);
954 document.addEventListener("mouseup", mouseup);
955 }
956 if ('ontouchstart' in window) {
cb17fed8
BA
957 // https://stackoverflow.com/a/42509310/12660887
958 document.addEventListener("touchstart", mousedown, {passive: false});
959 document.addEventListener("touchmove", mousemove, {passive: false});
960 document.addEventListener("touchend", mouseup, {passive: false});
41534b92 961 }
11625344 962 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
41534b92
BA
963 }
964
965 showChoices(moves, r) {
966 let container = document.getElementById(this.containerId);
967 let choices = document.createElement("div");
968 choices.id = "choices";
969 choices.style.width = r.width + "px";
970 choices.style.height = r.height + "px";
971 choices.style.left = r.x + "px";
972 choices.style.top = r.y + "px";
973 container.style.opacity = "0.5";
974 let boardContainer = document.getElementById("boardContainer");
975 boardContainer.appendChild(choices);
976 const squareWidth = this.getSquareWidth(r.width);
977 const firstUpLeft = (r.width - (moves.length * squareWidth)) / 2;
978 const firstUpTop = (r.height - squareWidth) / 2;
979 const color = moves[0].appear[0].c;
980 const callback = (m) => {
981 container.style.opacity = "1";
982 boardContainer.removeChild(choices);
983 this.playPlusVisual(m, r);
984 }
985 for (let i=0; i < moves.length; i++) {
986 let choice = document.createElement("div");
987 choice.classList.add("choice");
988 choice.style.width = squareWidth + "px";
989 choice.style.height = squareWidth + "px";
990 choice.style.left = (firstUpLeft + i * squareWidth) + "px";
991 choice.style.top = firstUpTop + "px";
992 choice.style.backgroundColor = "lightyellow";
993 choice.onclick = () => callback(moves[i]);
994 const piece = document.createElement("piece");
995 const pieceSpec = this.pieces(color)[moves[i].appear[0].p];
996 piece.classList.add(pieceSpec["class"]);
997 piece.classList.add(color == 'w' ? "white" : "black");
998 piece.style.width = "100%";
999 piece.style.height = "100%";
1000 choice.appendChild(piece);
1001 choices.appendChild(choice);
1002 }
1003 }
1004
1005 //////////////
1006 // BASIC UTILS
1007
1008 get size() {
1009 return { "x": 8, "y": 8 };
1010 }
1011
1012 // Color of thing on square (i,j). 'undefined' if square is empty
1013 getColor(i, j) {
1014 return this.board[i][j].charAt(0);
1015 }
1016
cc2c7183 1017 // Assume square i,j isn't empty
41534b92
BA
1018 getPiece(i, j) {
1019 return this.board[i][j].charAt(1);
1020 }
1021
cc2c7183
BA
1022 // Piece type on square (i,j)
1023 getPieceType(i, j) {
1024 const p = this.board[i][j].charAt(1);
1025 return C.CannibalKings[p] || p; //a cannibal king move as...
1026 }
1027
41534b92
BA
1028 // Get opponent color
1029 static GetOppCol(color) {
1030 return (color == "w" ? "b" : "w");
1031 }
1032
1033 // Can thing on square1 take thing on square2
1034 canTake([x1, y1], [x2, y2]) {
1035 return (
cc2c7183 1036 (this.getColor(x1, y1) !== this.getColor(x2, y2)) ||
41534b92
BA
1037 (
1038 (this.options["recycle"] || this.options["teleport"]) &&
cc2c7183
BA
1039 this.getPieceType(x2, y2) != "k"
1040 )
41534b92
BA
1041 );
1042 }
1043
1044 // Is (x,y) on the chessboard?
1045 onBoard(x, y) {
1046 return x >= 0 && x < this.size.x && y >= 0 && y < this.size.y;
1047 }
1048
1049 // Used in interface: 'side' arg == player color
1050 canIplay(x, y) {
1051 return (
1052 this.playerColor == this.turn &&
1053 (
1054 (typeof x == "number" && this.getColor(x, y) == this.turn) ||
1055 (typeof x == "string" && x == this.turn) //reserve
1056 )
1057 );
1058 }
1059
1060 ////////////////////////
1061 // PIECES SPECIFICATIONS
1062
1063 pieces(color) {
1064 const pawnShift = (color == "w" ? -1 : 1);
1065 return {
1066 'p': {
1067 "class": "pawn",
1068 steps: [[pawnShift, 0]],
1069 range: 1,
1070 attack: [[pawnShift, 1], [pawnShift, -1]]
1071 },
1072 // rook
1073 'r': {
1074 "class": "rook",
1075 steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]
1076 },
1077 // knight
1078 'n': {
1079 "class": "knight",
1080 steps: [
1081 [1, 2], [1, -2], [-1, 2], [-1, -2],
1082 [2, 1], [-2, 1], [2, -1], [-2, -1]
1083 ],
1084 range: 1
1085 },
1086 // bishop
1087 'b': {
1088 "class": "bishop",
1089 steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]
1090 },
1091 // queen
1092 'q': {
1093 "class": "queen",
1094 steps: [
1095 [0, 1], [0, -1], [1, 0], [-1, 0],
1096 [1, 1], [1, -1], [-1, 1], [-1, -1]
1097 ]
1098 },
1099 // king
1100 'k': {
1101 "class": "king",
1102 steps: [
1103 [0, 1], [0, -1], [1, 0], [-1, 0],
1104 [1, 1], [1, -1], [-1, 1], [-1, -1]
1105 ],
1106 range: 1
cc2c7183
BA
1107 },
1108 // Cannibal kings:
1109 's': { "class": "king-pawn" },
1110 'u': { "class": "king-rook" },
1111 'o': { "class": "king-knight" },
1112 'c': { "class": "king-bishop" },
1113 't': { "class": "king-queen" }
41534b92
BA
1114 };
1115 }
1116
41534b92
BA
1117 ////////////////////
1118 // MOVES GENERATION
1119
1120 // For Cylinder: get Y coordinate
1121 computeY(y) {
1122 if (!this.options["cylinder"]) return y;
1123 let res = y % this.size.y;
1124 if (res < 0) res += this.size.y;
1125 return res;
1126 }
1127
1128 // Stop at the first capture found
1129 atLeastOneCapture(color) {
1130 color = color || this.turn;
cc2c7183 1131 const oppCol = C.GetOppCol(color);
41534b92
BA
1132 for (let i = 0; i < this.size.x; i++) {
1133 for (let j = 0; j < this.size.y; j++) {
1134 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
cc2c7183 1135 const specs = this.pieces(color)[this.getPieceType(i, j)];
41534b92
BA
1136 const steps = specs.attack || specs.steps;
1137 outerLoop: for (let step of steps) {
1138 let [ii, jj] = [i + step[0], this.computeY(j + step[1])];
1139 let stepCounter = 1;
1140 while (this.onBoard(ii, jj) && this.board[ii][jj] == "") {
1141 if (specs.range <= stepCounter++) continue outerLoop;
1142 ii += step[0];
1143 jj = this.computeY(jj + step[1]);
1144 }
1145 if (
1146 this.onBoard(ii, jj) &&
1147 this.getColor(ii, jj) == oppCol &&
1148 this.filterValid(
1149 [this.getBasicMove([i, j], [ii, jj])]
1150 ).length >= 1
1151 ) {
1152 return true;
1153 }
1154 }
1155 }
1156 }
1157 }
1158 return false;
1159 }
1160
1161 getDropMovesFrom([c, p]) {
1162 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1163 // (but not necessarily otherwise)
cc2c7183 1164 if (this.reserve[c][p] == 0) return [];
41534b92
BA
1165 let moves = [];
1166 for (let i=0; i<this.size.x; i++) {
1167 for (let j=0; j<this.size.y; j++) {
1168 // TODO: rather simplify this "if" and add post-condition: more general
1169 if (
1170 this.board[i][j] == "" &&
1171 (!this.options["dark"] || this.enlightened[i][j]) &&
1172 (
cc2c7183 1173 p != "p" ||
41534b92
BA
1174 (c == 'w' && i < this.size.x - 1) ||
1175 (c == 'b' && i > 0)
1176 )
1177 ) {
1178 moves.push(
1179 new Move({
1180 start: {x: c, y: p},
1181 end: {x: i, y: j},
1182 appear: [new PiPo({x: i, y: j, c: c, p: p})],
1183 vanish: []
1184 })
1185 );
1186 }
1187 }
1188 }
1189 return moves;
1190 }
1191
1192 // All possible moves from selected square
c7bf7b1b 1193 getPotentialMovesFrom(sq, color) {
41534b92
BA
1194 if (typeof sq[0] == "string") return this.getDropMovesFrom(sq);
1195 if (this.options["madrasi"] && this.isImmobilized(sq)) return [];
cc2c7183 1196 const piece = this.getPieceType(sq[0], sq[1]);
41534b92 1197 let moves;
cc2c7183 1198 if (piece == "p") moves = this.getPotentialPawnMoves(sq);
41534b92
BA
1199 else moves = this.getPotentialMovesOf(piece, sq);
1200 if (
cc2c7183 1201 piece == "k" &&
41534b92
BA
1202 this.hasCastle &&
1203 this.castleFlags[color || this.turn].some(v => v < this.size.y)
1204 ) {
1205 Array.prototype.push.apply(moves, this.getCastleMoves(sq));
1206 }
1207 return this.postProcessPotentialMoves(moves);
1208 }
1209
1210 postProcessPotentialMoves(moves) {
1211 if (moves.length == 0) return [];
1212 const color = this.getColor(moves[0].start.x, moves[0].start.y);
cc2c7183 1213 const oppCol = C.GetOppCol(color);
41534b92
BA
1214
1215 if (this.options["capture"] && this.atLeastOneCapture()) {
1216 // Filter out non-capturing moves (not using m.vanish because of
1217 // self captures of Recycle and Teleport).
1218 moves = moves.filter(m => {
1219 return (
1220 this.board[m.end.x][m.end.y] != "" &&
1221 this.getColor(m.end.x, m.end.y) == oppCol
1222 );
1223 });
1224 }
1225
1226 if (this.options["atomic"]) {
1227 moves.forEach(m => {
1228 if (
1229 this.board[m.end.x][m.end.y] != "" &&
1230 this.getColor(m.end.x, m.end.y) == oppCol
1231 ) {
1232 // Explosion!
1233 let steps = [
1234 [-1, -1],
1235 [-1, 0],
1236 [-1, 1],
1237 [0, -1],
1238 [0, 1],
1239 [1, -1],
1240 [1, 0],
1241 [1, 1]
1242 ];
1243 for (let step of steps) {
1244 let x = m.end.x + step[0];
1245 let y = this.computeY(m.end.y + step[1]);
1246 if (
1247 this.onBoard(x, y) &&
1248 this.board[x][y] != "" &&
cc2c7183 1249 this.getPieceType(x, y) != "p"
41534b92
BA
1250 ) {
1251 m.vanish.push(
1252 new PiPo({
1253 p: this.getPiece(x, y),
1254 c: this.getColor(x, y),
1255 x: x,
1256 y: y
1257 })
1258 );
1259 }
1260 }
1261 if (!this.options["rifle"]) m.appear.pop(); //nothin appears
1262 }
1263 });
1264 }
cc2c7183
BA
1265
1266 if (
1267 this.options["cannibal"] &&
1268 this.options["rifle"] &&
1269 this.pawnSpecs.promotions
1270 ) {
1271 // In this case a rifle-capture from last rank may promote a pawn
1272 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1273 let newMoves = [];
1274 moves.forEach(m => {
1275 if (
1276 m.start.x == lastRank &&
1277 m.appear.length >= 1 &&
1278 m.appear[0].p == "p" &&
1279 m.appear[0].x == m.start.x &&
1280 m.appear[0].y == m.start.y
1281 ) {
1282 const promotionPiece0 = this.pawnSpecs.promotions[0];
1283 m.appear[0].p = this.pawnSpecs.promotions[0];
1284 for (let i=1; i<this.pawnSpecs.promotions.length; i++) {
1285 let newMv = JSON.parse(JSON.stringify(m));
1286 newMv.appear[0].p = this.pawnSpecs.promotions[i];
1287 newMoves.push(newMv);
1288 }
1289 }
1290 });
1291 Array.prototype.push.apply(moves, newMoves);
1292 }
1293
41534b92
BA
1294 return moves;
1295 }
1296
cc2c7183
BA
1297 static get CannibalKings() {
1298 return {
1299 "s": "p",
1300 "u": "r",
1301 "o": "n",
1302 "c": "b",
1303 "t": "q"
1304 };
1305 }
1306
1307 static get CannibalKingCode() {
1308 return {
1309 "p": "s",
1310 "r": "u",
1311 "n": "o",
1312 "b": "c",
1313 "q": "t",
1314 "k": "k"
1315 };
1316 }
1317
1318 isKing(symbol) {
1319 return (
1320 symbol == 'k' ||
1321 (this.options["cannibal"] && C.CannibalKings[symbol])
1322 );
1323 }
1324
41534b92
BA
1325 // For Madrasi:
1326 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1327 isImmobilized([x, y]) {
1328 const color = this.getColor(x, y);
cc2c7183
BA
1329 const oppCol = C.GetOppCol(color);
1330 const piece = this.getPieceType(x, y);
41534b92
BA
1331 const stepSpec = this.pieces(color)[piece];
1332 let [steps, range] = [stepSpec.attack || stepSpec.steps, stepSpec.range];
1333 outerLoop: for (let step of steps) {
1334 let [i, j] = [x + step[0], y + step[1]];
1335 let stepCounter = 1;
1336 while (this.onBoard(i, j) && this.board[i][j] == "") {
1337 if (range <= stepCounter++) continue outerLoop;
1338 i += step[0];
1339 j = this.computeY(j + step[1]);
1340 }
1341 if (
1342 this.onBoard(i, j) &&
1343 this.getColor(i, j) == oppCol &&
cc2c7183 1344 this.getPieceType(i, j) == piece
41534b92
BA
1345 ) {
1346 return true;
1347 }
1348 }
1349 return false;
1350 }
1351
1352 // Generic method to find possible moves of "sliding or jumping" pieces
1353 getPotentialMovesOf(piece, [x, y]) {
1354 const color = this.getColor(x, y);
1355 const stepSpec = this.pieces(color)[piece];
1356 let [steps, range] = [stepSpec.steps, stepSpec.range];
1357 let moves = [];
1358 let explored = {}; //for Cylinder mode
1359 outerLoop: for (let step of steps) {
1360 let [i, j] = [x + step[0], this.computeY(y + step[1])];
1361 let stepCounter = 1;
1362 while (
1363 this.onBoard(i, j) &&
1364 this.board[i][j] == "" &&
1365 !explored[i + "." + j]
1366 ) {
1367 explored[i + "." + j] = true;
1368 moves.push(this.getBasicMove([x, y], [i, j]));
1369 if (range <= stepCounter++) continue outerLoop;
1370 i += step[0];
1371 j = this.computeY(j + step[1]);
1372 }
1373 if (
1374 this.onBoard(i, j) &&
1375 (
1376 !this.options["zen"] ||
cc2c7183 1377 this.getPieceType(i, j) == "k" ||
41534b92
BA
1378 this.getColor(i, j) == color //OK for Recycle and Teleport
1379 ) &&
1380 this.canTake([x, y], [i, j]) &&
1381 !explored[i + "." + j]
1382 ) {
1383 explored[i + "." + j] = true;
1384 moves.push(this.getBasicMove([x, y], [i, j]));
1385 }
1386 }
1387 if (this.options["zen"])
1388 Array.prototype.push.apply(moves, this.getZenCaptures(x, y));
1389 return moves;
1390 }
1391
1392 getZenCaptures(x, y) {
1393 let moves = [];
1394 // Find reverse captures (opponent takes)
1395 const color = this.getColor(x, y);
cc2c7183
BA
1396 const pieceType = this.getPieceType(x, y);
1397 const oppCol = C.GetOppCol(color);
41534b92
BA
1398 const pieces = this.pieces(oppCol);
1399 Object.keys(pieces).forEach(p => {
cc2c7183
BA
1400 if (
1401 p == "k" ||
1402 (this.options["cannibal"] && C.CannibalKings[p])
1403 ) {
1404 return; //king isn't captured this way
1405 }
41534b92 1406 const steps = pieces[p].attack || pieces[p].steps;
67c5c198 1407 if (!steps) return; //cannibal king for example (TODO...)
41534b92
BA
1408 const range = pieces[p].range;
1409 steps.forEach(s => {
1410 // From x,y: revert step
1411 let [i, j] = [x - s[0], this.computeY(y - s[1])];
1412 let stepCounter = 1;
1413 while (this.onBoard(i, j) && this.board[i][j] == "") {
1414 if (range <= stepCounter++) return;
1415 i -= s[0];
1416 j = this.computeY(j - s[1]);
1417 }
1418 if (
1419 this.onBoard(i, j) &&
cc2c7183 1420 this.getPieceType(i, j) == p &&
41534b92
BA
1421 this.getColor(i, j) == oppCol && //condition for Recycle & Teleport
1422 this.canTake([i, j], [x, y])
1423 ) {
cc2c7183 1424 if (pieceType != "p") moves.push(this.getBasicMove([x, y], [i, j]));
41534b92
BA
1425 else this.addPawnMoves([x, y], [i, j], moves);
1426 }
1427 });
1428 });
1429 return moves;
1430 }
1431
1432 // Build a regular move from its initial and destination squares.
1433 // tr: transformation
1434 getBasicMove([sx, sy], [ex, ey], tr) {
1435 const initColor = this.getColor(sx, sy);
cc2c7183 1436 const initPiece = this.getPiece(sx, sy);
41534b92
BA
1437 const destColor = (this.board[ex][ey] != "" ? this.getColor(ex, ey) : "");
1438 let mv = new Move({
1439 appear: [],
1440 vanish: [],
1441 start: {x:sx, y:sy},
1442 end: {x:ex, y:ey}
1443 });
1444 if (
1445 !this.options["rifle"] ||
1446 this.board[ex][ey] == "" ||
1447 destColor == initColor //Recycle, Teleport
1448 ) {
1449 mv.appear = [
1450 new PiPo({
1451 x: ex,
1452 y: ey,
1453 c: !!tr ? tr.c : initColor,
1454 p: !!tr ? tr.p : initPiece
1455 })
1456 ];
1457 mv.vanish = [
1458 new PiPo({
1459 x: sx,
1460 y: sy,
1461 c: initColor,
1462 p: initPiece
1463 })
1464 ];
1465 }
1466 if (this.board[ex][ey] != "") {
1467 mv.vanish.push(
1468 new PiPo({
1469 x: ex,
1470 y: ey,
1471 c: this.getColor(ex, ey),
cc2c7183 1472 p: this.getPiece(ex, ey)
41534b92
BA
1473 })
1474 );
1475 if (this.options["rifle"])
1476 // Rifle captures are tricky in combination with Atomic etc,
1477 // so it's useful to mark the move :
1478 mv.capture = true;
1479 if (this.options["cannibal"] && destColor != initColor) {
1480 const lastIdx = mv.vanish.length - 1;
cc2c7183
BA
1481 let trPiece = mv.vanish[lastIdx].p;
1482 if (this.isKing(this.getPiece(sx, sy)))
1483 trPiece = C.CannibalKingCode[trPiece];
1484 if (mv.appear.length >= 1) mv.appear[0].p = trPiece;
41534b92
BA
1485 else if (this.options["rifle"]) {
1486 mv.appear.unshift(
1487 new PiPo({
1488 x: sx,
1489 y: sy,
1490 c: initColor,
cc2c7183 1491 p: trPiece
41534b92
BA
1492 })
1493 );
1494 mv.vanish.unshift(
1495 new PiPo({
1496 x: sx,
1497 y: sy,
1498 c: initColor,
1499 p: initPiece
1500 })
1501 );
1502 }
1503 }
1504 }
1505 return mv;
1506 }
1507
1508 // En-passant square, if any
1509 getEpSquare(moveOrSquare) {
1510 if (typeof moveOrSquare === "string") {
1511 const square = moveOrSquare;
1512 if (square == "-") return undefined;
cc2c7183 1513 return C.SquareToCoords(square);
41534b92
BA
1514 }
1515 // Argument is a move:
1516 const move = moveOrSquare;
1517 const s = move.start,
1518 e = move.end;
1519 if (
1520 s.y == e.y &&
1521 Math.abs(s.x - e.x) == 2 &&
1522 // Next conditions for variants like Atomic or Rifle, Recycle...
cc2c7183
BA
1523 (move.appear.length > 0 && move.appear[0].p == "p") &&
1524 (move.vanish.length > 0 && move.vanish[0].p == "p")
41534b92
BA
1525 ) {
1526 return {
1527 x: (s.x + e.x) / 2,
1528 y: s.y
1529 };
1530 }
1531 return undefined; //default
1532 }
1533
1534 // Special case of en-passant captures: treated separately
1535 getEnpassantCaptures([x, y], shiftX) {
1536 const color = this.getColor(x, y);
cc2c7183 1537 const oppCol = C.GetOppCol(color);
41534b92
BA
1538 let enpassantMove = null;
1539 if (
1540 !!this.epSquare &&
1541 this.epSquare.x == x + shiftX &&
1542 Math.abs(this.computeY(this.epSquare.y - y)) == 1 &&
1543 this.getColor(x, this.epSquare.y) == oppCol //Doublemove guard...
1544 ) {
1545 const [epx, epy] = [this.epSquare.x, this.epSquare.y];
1546 this.board[epx][epy] = oppCol + "p";
1547 enpassantMove = this.getBasicMove([x, y], [epx, epy]);
1548 this.board[epx][epy] = "";
1549 const lastIdx = enpassantMove.vanish.length - 1; //think Rifle
1550 enpassantMove.vanish[lastIdx].x = x;
1551 }
1552 return !!enpassantMove ? [enpassantMove] : [];
1553 }
1554
f8b43ef7
BA
1555 // Consider all potential promotions.
1556 // NOTE: "promotions" arg = special override for Hiddenqueen variant
41534b92 1557 addPawnMoves([x1, y1], [x2, y2], moves, promotions) {
cc2c7183 1558 let finalPieces = ["p"];
41534b92 1559 const color = this.getColor(x1, y1);
a80b660e 1560 const oppCol = C.GetOppCol(color);
41534b92 1561 const lastRank = (color == "w" ? 0 : this.size.x - 1);
f8b43ef7
BA
1562 const promotionOk =
1563 x2 == lastRank && (!this.options["rifle"] || this.board[x2][y2] == "");
1564 if (promotionOk && !this.options["pawnfall"]) {
a80b660e
BA
1565 if (
1566 this.options["cannibal"] &&
1567 this.board[x2][y2] != "" &&
1568 this.getColor(x2, y2) == oppCol
1569 ) {
1570 finalPieces = [this.getPieceType(x2, y2)];
1571 }
1572 else if (promotions) finalPieces = promotions;
41534b92
BA
1573 else if (this.pawnSpecs.promotions)
1574 finalPieces = this.pawnSpecs.promotions;
1575 }
1576 for (let piece of finalPieces) {
f8b43ef7
BA
1577 const tr = !this.options["pawnfall"] && piece != "p"
1578 ? { c: color, p: piece }
1579 : null;
1580 let newMove = this.getBasicMove([x1, y1], [x2, y2], tr);
1581 if (promotionOk && this.options["pawnfall"]) {
1582 newMove.appear.shift();
1583 newMove.pawnfall = true; //required in prePlay()
1584 }
1585 moves.push(newMove);
41534b92
BA
1586 }
1587 }
1588
1589 // What are the pawn moves from square x,y ?
1590 getPotentialPawnMoves([x, y], promotions) {
1591 const color = this.getColor(x, y); //this.turn doesn't work for Dark mode
1592 const [sizeX, sizeY] = [this.size.x, this.size.y];
1593 const pawnShiftX = this.pawnSpecs.directions[color];
1594 const firstRank = (color == "w" ? sizeX - 1 : 0);
1595 const forward = (color == 'w' ? -1 : 1);
1596
1597 // Pawn movements in shiftX direction:
1598 const getPawnMoves = (shiftX) => {
1599 let moves = [];
1600 // NOTE: next condition is generally true (no pawn on last rank)
1601 if (x + shiftX >= 0 && x + shiftX < sizeX) {
1602 if (this.board[x + shiftX][y] == "") {
1603 // One square forward (or backward)
1604 this.addPawnMoves([x, y], [x + shiftX, y], moves, promotions);
1605 // Next condition because pawns on 1st rank can generally jump
1606 if (
1607 this.pawnSpecs.twoSquares &&
1608 (
1609 (
1610 color == 'w' &&
1611 x >= this.size.x - 1 - this.pawnSpecs.initShift['w']
1612 )
1613 ||
1614 (color == 'b' && x <= this.pawnSpecs.initShift['b'])
1615 )
1616 ) {
1617 if (
1618 shiftX == forward &&
1619 this.board[x + 2 * shiftX][y] == ""
1620 ) {
1621 // Two squares jump
1622 moves.push(this.getBasicMove([x, y], [x + 2 * shiftX, y]));
1623 if (
1624 this.pawnSpecs.threeSquares &&
1625 this.board[x + 3 * shiftX, y] == ""
1626 ) {
1627 // Three squares jump
1628 moves.push(this.getBasicMove([x, y], [x + 3 * shiftX, y]));
1629 }
1630 }
1631 }
1632 }
1633 // Captures
1634 if (this.pawnSpecs.canCapture) {
1635 for (let shiftY of [-1, 1]) {
1636 const yCoord = this.computeY(y + shiftY);
1637 if (yCoord >= 0 && yCoord < sizeY) {
1638 if (
1639 this.board[x + shiftX][yCoord] != "" &&
1640 this.canTake([x, y], [x + shiftX, yCoord]) &&
1641 (
1642 !this.options["zen"] ||
cc2c7183 1643 this.getPieceType(x + shiftX, yCoord) == "k"
41534b92
BA
1644 )
1645 ) {
1646 this.addPawnMoves(
1647 [x, y], [x + shiftX, yCoord],
1648 moves, promotions
1649 );
1650 }
1651 if (
1652 this.pawnSpecs.captureBackward && shiftX == forward &&
1653 x - shiftX >= 0 && x - shiftX < this.size.x &&
1654 this.board[x - shiftX][yCoord] != "" &&
1655 this.canTake([x, y], [x - shiftX, yCoord]) &&
1656 (
1657 !this.options["zen"] ||
cc2c7183 1658 this.getPieceType(x + shiftX, yCoord) == "k"
41534b92
BA
1659 )
1660 ) {
1661 this.addPawnMoves(
1662 [x, y], [x - shiftX, yCoord],
1663 moves, promotions
1664 );
1665 }
1666 }
1667 }
1668 }
1669 }
1670 return moves;
1671 }
1672
1673 let pMoves = getPawnMoves(pawnShiftX);
1674 if (this.pawnSpecs.bidirectional)
1675 pMoves = pMoves.concat(getPawnMoves(-pawnShiftX));
1676
1677 if (this.hasEnpassant) {
1678 // NOTE: backward en-passant captures are not considered
1679 // because no rules define them (for now).
1680 Array.prototype.push.apply(
1681 pMoves,
1682 this.getEnpassantCaptures([x, y], pawnShiftX)
1683 );
1684 }
1685
1686 if (this.options["zen"])
1687 Array.prototype.push.apply(pMoves, this.getZenCaptures(x, y));
1688
1689 return pMoves;
1690 }
1691
1692 // "castleInCheck" arg to let some variants castle under check
1693 getCastleMoves([x, y], finalSquares, castleInCheck, castleWith) {
1694 const c = this.getColor(x, y);
1695
1696 // Castling ?
cc2c7183 1697 const oppCol = C.GetOppCol(c);
41534b92
BA
1698 let moves = [];
1699 // King, then rook:
1700 finalSquares =
1701 finalSquares || [ [2, 3], [this.size.y - 2, this.size.y - 3] ];
cc2c7183 1702 const castlingKing = this.getPiece(x, y);
41534b92
BA
1703 castlingCheck: for (
1704 let castleSide = 0;
1705 castleSide < 2;
1706 castleSide++ //large, then small
1707 ) {
1708 if (this.castleFlags[c][castleSide] >= this.size.y) continue;
1709 // If this code is reached, rook and king are on initial position
1710
1711 // NOTE: in some variants this is not a rook
1712 const rookPos = this.castleFlags[c][castleSide];
cc2c7183 1713 const castlingPiece = this.getPiece(x, rookPos);
41534b92
BA
1714 if (
1715 this.board[x][rookPos] == "" ||
1716 this.getColor(x, rookPos) != c ||
1717 (!!castleWith && !castleWith.includes(castlingPiece))
1718 ) {
1719 // Rook is not here, or changed color (see Benedict)
1720 continue;
1721 }
1722 // Nothing on the path of the king ? (and no checks)
1723 const finDist = finalSquares[castleSide][0] - y;
1724 let step = finDist / Math.max(1, Math.abs(finDist));
1725 let i = y;
1726 do {
1727 if (
1728 (!castleInCheck && this.underCheck([x, i], oppCol)) ||
1729 (
1730 this.board[x][i] != "" &&
1731 // NOTE: next check is enough, because of chessboard constraints
1732 (this.getColor(x, i) != c || ![rookPos, y].includes(i))
1733 )
1734 ) {
1735 continue castlingCheck;
1736 }
1737 i += step;
1738 } while (i != finalSquares[castleSide][0]);
1739 // Nothing on the path to the rook?
1740 step = (castleSide == 0 ? -1 : 1);
1741 for (i = y + step; i != rookPos; i += step) {
1742 if (this.board[x][i] != "") continue castlingCheck;
1743 }
1744
1745 // Nothing on final squares, except maybe king and castling rook?
1746 for (i = 0; i < 2; i++) {
1747 if (
1748 finalSquares[castleSide][i] != rookPos &&
1749 this.board[x][finalSquares[castleSide][i]] != "" &&
1750 (
1751 finalSquares[castleSide][i] != y ||
1752 this.getColor(x, finalSquares[castleSide][i]) != c
1753 )
1754 ) {
1755 continue castlingCheck;
1756 }
1757 }
1758
1759 // If this code is reached, castle is valid
1760 moves.push(
1761 new Move({
1762 appear: [
1763 new PiPo({
1764 x: x,
1765 y: finalSquares[castleSide][0],
1766 p: castlingKing,
1767 c: c
1768 }),
1769 new PiPo({
1770 x: x,
1771 y: finalSquares[castleSide][1],
1772 p: castlingPiece,
1773 c: c
1774 })
1775 ],
1776 vanish: [
1777 // King might be initially disguised (Titan...)
1778 new PiPo({ x: x, y: y, p: castlingKing, c: c }),
1779 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
1780 ],
1781 end:
1782 Math.abs(y - rookPos) <= 2
1783 ? { x: x, y: rookPos }
1784 : { x: x, y: y + 2 * (castleSide == 0 ? -1 : 1) }
1785 })
1786 );
1787 }
1788
1789 return moves;
1790 }
1791
1792 ////////////////////
1793 // MOVES VALIDATION
1794
1795 // Is (king at) given position under check by "color" ?
1796 underCheck([x, y], color) {
f8b43ef7 1797 if (this.options["taking"] || this.options["dark"]) return false;
cc2c7183 1798 color = color || C.GetOppCol(this.getColor(x, y));
41534b92
BA
1799 const pieces = this.pieces(color);
1800 return Object.keys(pieces).some(p => {
1801 return this.isAttackedBy([x, y], p, color, pieces[p]);
1802 });
1803 }
1804
1805 isAttackedBy([x, y], piece, color, stepSpec) {
1806 const steps = stepSpec.attack || stepSpec.steps;
cc2c7183 1807 if (!steps) return false; //cannibal king, for example
41534b92
BA
1808 const range = stepSpec.range;
1809 let explored = {}; //for Cylinder mode
1810 outerLoop: for (let step of steps) {
1811 let rx = x - step[0],
1812 ry = this.computeY(y - step[1]);
1813 let stepCounter = 1;
1814 while (
1815 this.onBoard(rx, ry) &&
1816 this.board[rx][ry] == "" &&
1817 !explored[rx + "." + ry]
1818 ) {
1819 explored[rx + "." + ry] = true;
1820 if (range <= stepCounter++) continue outerLoop;
1821 rx -= step[0];
1822 ry = this.computeY(ry - step[1]);
1823 }
1824 if (
1825 this.onBoard(rx, ry) &&
1826 this.board[rx][ry] != "" &&
cc2c7183 1827 this.getPieceType(rx, ry) == piece &&
41534b92
BA
1828 this.getColor(rx, ry) == color &&
1829 (!this.options["madrasi"] || !this.isImmobilized([rx, ry]))
1830 ) {
1831 return true;
1832 }
1833 }
1834 return false;
1835 }
1836
1837 // Stop at first king found (TODO: multi-kings)
1838 searchKingPos(color) {
1839 for (let i=0; i < this.size.x; i++) {
1840 for (let j=0; j < this.size.y; j++) {
cc2c7183
BA
1841 if (this.getColor(i, j) == color && this.isKing(this.getPiece(i, j)))
1842 return [i, j];
41534b92
BA
1843 }
1844 }
1845 return [-1, -1]; //king not found
1846 }
1847
1848 filterValid(moves) {
1849 if (moves.length == 0) return [];
1850 const color = this.turn;
cc2c7183 1851 const oppCol = C.GetOppCol(color);
41534b92
BA
1852 if (this.options["balance"] && [1, 3].includes(this.movesCount)) {
1853 // Forbid moves either giving check or exploding opponent's king:
1854 const oppKingPos = this.searchKingPos(oppCol);
1855 moves = moves.filter(m => {
1856 if (
cc2c7183
BA
1857 m.vanish.some(v => v.c == oppCol && v.p == "k") &&
1858 m.appear.every(a => a.c != oppCol || a.p != "k")
41534b92
BA
1859 )
1860 return false;
1861 this.playOnBoard(m);
1862 const res = !this.underCheck(oppKingPos, color);
1863 this.undoOnBoard(m);
1864 return res;
1865 });
1866 }
f8b43ef7 1867 if (this.options["taking"] || this.options["dark"]) return moves;
41534b92
BA
1868 const kingPos = this.searchKingPos(color);
1869 let filtered = {}; //avoid re-checking similar moves (promotions...)
1870 return moves.filter(m => {
1871 const key = m.start.x + m.start.y + '.' + m.end.x + m.end.y;
1872 if (!filtered[key]) {
1873 this.playOnBoard(m);
1874 let square = kingPos,
1875 res = true; //a priori valid
cc2c7183
BA
1876 if (m.vanish.some(v => {
1877 return (v.p == "k" || C.CannibalKings[v.p]) && v.c == color;
1878 })) {
41534b92
BA
1879 // Search king in appear array:
1880 const newKingIdx =
cc2c7183
BA
1881 m.appear.findIndex(a => {
1882 return (a.p == "k" || C.CannibalKings[a.p]) && a.c == color;
1883 });
41534b92
BA
1884 if (newKingIdx >= 0)
1885 square = [m.appear[newKingIdx].x, m.appear[newKingIdx].y];
1886 else res = false;
1887 }
1888 res &&= !this.underCheck(square, oppCol);
1889 this.undoOnBoard(m);
1890 filtered[key] = res;
1891 return res;
1892 }
1893 return filtered[key];
1894 });
1895 }
1896
1897 /////////////////
1898 // MOVES PLAYING
1899
1900 // Aggregate flags into one object
1901 aggregateFlags() {
1902 return this.castleFlags;
1903 }
1904
1905 // Reverse operation
1906 disaggregateFlags(flags) {
1907 this.castleFlags = flags;
1908 }
1909
1910 // Apply a move on board
1911 playOnBoard(move) {
1912 for (let psq of move.vanish) this.board[psq.x][psq.y] = "";
1913 for (let psq of move.appear) this.board[psq.x][psq.y] = psq.c + psq.p;
1914 }
1915 // Un-apply the played move
1916 undoOnBoard(move) {
1917 for (let psq of move.appear) this.board[psq.x][psq.y] = "";
1918 for (let psq of move.vanish) this.board[psq.x][psq.y] = psq.c + psq.p;
1919 }
1920
1921 updateCastleFlags(move) {
1922 // Update castling flags if start or arrive from/at rook/king locations
1923 move.appear.concat(move.vanish).forEach(psq => {
1924 if (
1925 this.board[psq.x][psq.y] != "" &&
cc2c7183 1926 this.getPieceType(psq.x, psq.y) == "k"
41534b92
BA
1927 ) {
1928 this.castleFlags[psq.c] = [this.size.y, this.size.y];
1929 }
1930 // NOTE: not "else if" because king can capture enemy rook...
cc2c7183
BA
1931 let c = "";
1932 if (psq.x == 0) c = "b";
1933 else if (psq.x == this.size.x - 1) c = "w";
1934 if (c != "") {
41534b92
BA
1935 const fidx = this.castleFlags[c].findIndex(f => f == psq.y);
1936 if (fidx >= 0) this.castleFlags[c][fidx] = this.size.y;
1937 }
1938 });
1939 }
1940
1941 prePlay(move) {
1942 if (
1943 typeof move.start.x == "number" &&
cc2c7183 1944 (!this.options["teleport"] || this.subTurnTeleport == 1)
41534b92
BA
1945 ) {
1946 // OK, not a drop move
1947 if (
1948 this.hasCastle &&
1949 // If flags already off, no need to re-check:
1950 Object.keys(this.castleFlags).some(c => {
1951 return this.castleFlags[c].some(val => val < this.size.y)})
1952 ) {
1953 this.updateCastleFlags(move);
1954 }
cc2c7183 1955 const initSquare = C.CoordsToSquare(move.start);
41534b92
BA
1956 if (
1957 this.options["crazyhouse"] &&
1958 (!this.options["rifle"] || !move.capture)
1959 ) {
1960 if (this.ispawn[initSquare]) {
1961 delete this.ispawn[initSquare];
cc2c7183 1962 this.ispawn[C.CoordsToSquare(move.end)] = true;
41534b92
BA
1963 }
1964 else if (
cc2c7183
BA
1965 move.vanish[0].p == "p" &&
1966 move.appear[0].p != "p"
41534b92 1967 ) {
cc2c7183 1968 this.ispawn[C.CoordsToSquare(move.end)] = true;
41534b92
BA
1969 }
1970 }
1971 }
1972 const minSize = Math.min(move.appear.length, move.vanish.length);
f8b43ef7 1973 if (this.hasReserve && !move.pawnfall) {
41534b92
BA
1974 const color = this.turn;
1975 for (let i=minSize; i<move.appear.length; i++) {
1976 // Something appears = dropped on board (some exceptions, Chakart...)
1977 const piece = move.appear[i].p;
1978 this.updateReserve(color, piece, this.reserve[color][piece] - 1);
1979 }
1980 for (let i=minSize; i<move.vanish.length; i++) {
1981 // Something vanish: add to reserve except if recycle & opponent
1982 const piece = move.vanish[i].p;
1983 if (this.options["crazyhouse"] || move.vanish[i].c == color)
1984 this.updateReserve(color, piece, this.reserve[color][piece] + 1);
1985 }
1986 }
1987 }
1988
1989 play(move) {
1990 this.prePlay(move);
1991 if (this.hasEnpassant) this.epSquare = this.getEpSquare(move);
1992 this.playOnBoard(move);
1993 this.postPlay(move);
1994 }
1995
1996 postPlay(move) {
1997 const color = this.turn;
cc2c7183 1998 const oppCol = C.GetOppCol(color);
41534b92
BA
1999 if (this.options["dark"]) this.updateEnlightened(true);
2000 if (this.options["teleport"]) {
2001 if (
cc2c7183 2002 this.subTurnTeleport == 1 &&
41534b92
BA
2003 move.vanish.length > move.appear.length &&
2004 move.vanish[move.vanish.length - 1].c == color
2005 ) {
2006 const v = move.vanish[move.vanish.length - 1];
2007 this.captured = {x: v.x, y: v.y, c: v.c, p: v.p};
cc2c7183 2008 this.subTurnTeleport = 2;
41534b92
BA
2009 return;
2010 }
cc2c7183 2011 this.subTurnTeleport = 1;
41534b92
BA
2012 this.captured = null;
2013 }
2014 if (this.options["balance"]) {
2015 if (![1, 3].includes(this.movesCount)) this.turn = oppCol;
2016 }
2017 else {
2018 if (
2019 (
2020 this.options["doublemove"] &&
2021 this.movesCount >= 1 &&
2022 this.subTurn == 1
2023 ) ||
2024 (this.options["progressive"] && this.subTurn <= this.movesCount)
2025 ) {
2026 const oppKingPos = this.searchKingPos(oppCol);
2027 if (oppKingPos[0] >= 0 && !this.underCheck(oppKingPos, color)) {
2028 this.subTurn++;
2029 return;
2030 }
2031 }
2032 this.turn = oppCol;
2033 }
2034 this.movesCount++;
2035 this.subTurn = 1;
2036 }
2037
2038 // "Stop at the first move found"
2039 atLeastOneMove(color) {
2040 color = color || this.turn;
2041 for (let i = 0; i < this.size.x; i++) {
2042 for (let j = 0; j < this.size.y; j++) {
2043 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
cc2c7183
BA
2044 // NOTE: in fact searching for all potential moves from i,j.
2045 // I don't believe this is an issue, for now at least.
41534b92
BA
2046 const moves = this.getPotentialMovesFrom([i, j]);
2047 if (moves.some(m => this.filterValid([m]).length >= 1)) return true;
2048 }
2049 }
2050 }
2051 if (this.hasReserve && this.reserve[color]) {
2052 for (let p of Object.keys(this.reserve[color])) {
2053 const moves = this.getDropMovesFrom([color, p]);
2054 if (moves.some(m => this.filterValid([m]).length >= 1)) return true;
2055 }
2056 }
2057 return false;
2058 }
2059
2060 // What is the score ? (Interesting if game is over)
2061 getCurrentScore(move) {
2062 const color = this.turn;
cc2c7183 2063 const oppCol = C.GetOppCol(color);
41534b92
BA
2064 const kingPos = [this.searchKingPos(color), this.searchKingPos(oppCol)];
2065 if (kingPos[0][0] < 0 && kingPos[1][0] < 0) return "1/2";
2066 if (kingPos[0][0] < 0) return (color == "w" ? "0-1" : "1-0");
2067 if (kingPos[1][0] < 0) return (color == "w" ? "1-0" : "0-1");
2068 if (this.atLeastOneMove()) return "*";
2069 // No valid move: stalemate or checkmate?
2070 if (!this.underCheck(kingPos, color)) return "1/2";
2071 // OK, checkmate
2072 return (color == "w" ? "0-1" : "1-0");
2073 }
2074
cc2c7183 2075 // NOTE: quite suboptimal for eg. Benedict (not a big deal I think)
41534b92
BA
2076 playVisual(move, r) {
2077 move.vanish.forEach(v => {
2078 if (!this.enlightened || this.enlightened[v.x][v.y]) {
2079 this.g_pieces[v.x][v.y].remove();
2080 this.g_pieces[v.x][v.y] = null;
2081 }
2082 });
2083 let container = document.getElementById(this.containerId);
2084 if (!r) r = container.getBoundingClientRect();
2085 const pieceWidth = this.getPieceWidth(r.width);
2086 move.appear.forEach(a => {
2087 if (this.enlightened && !this.enlightened[a.x][a.y]) return;
2088 this.g_pieces[a.x][a.y] = document.createElement("piece");
2089 this.g_pieces[a.x][a.y].classList.add(this.pieces()[a.p]["class"]);
2090 this.g_pieces[a.x][a.y].classList.add(a.c == "w" ? "white" : "black");
2091 this.g_pieces[a.x][a.y].style.width = pieceWidth + "px";
2092 this.g_pieces[a.x][a.y].style.height = pieceWidth + "px";
2093 const [ip, jp] = this.getPixelPosition(a.x, a.y, r);
2094 this.g_pieces[a.x][a.y].style.transform = `translate(${ip}px,${jp}px)`;
2095 container.appendChild(this.g_pieces[a.x][a.y]);
2096 });
2097 }
2098
2099 playPlusVisual(move, r) {
2100 this.playVisual(move, r);
2101 this.play(move);
2102 this.afterPlay(move); //user method
2103 }
2104
2105 // Assumes reserve on top (usage case otherwise? TODO?)
2106 getReserveShift(c, p, r) {
2107 let nbR = 0,
2108 ridx = 0;
2109 for (let pi of Object.keys(this.reserve[c])) {
2110 if (this.reserve[c][pi] == 0) continue;
2111 if (pi == p) ridx = nbR;
2112 nbR++;
2113 }
2114 const rsqSize = this.getReserveSquareSize(r.width, nbR);
f8b43ef7 2115 return [-ridx * rsqSize, rsqSize]; //slightly inaccurate... TODO?
41534b92
BA
2116 }
2117
2118 animate(move, callback) {
2119 if (this.noAnimate) {
2120 callback();
2121 return;
2122 }
2123 const [i1, j1] = [move.start.x, move.start.y];
2124 const dropMove = (typeof i1 == "string");
2125 const startArray = (dropMove ? this.r_pieces : this.g_pieces);
2126 let startPiece = startArray[i1][j1];
2127 let container = document.getElementById(this.containerId);
2128 const clonePiece = (
2129 !dropMove &&
2130 this.options["rifle"] ||
cc2c7183 2131 (this.options["teleport"] && this.subTurnTeleport == 2)
41534b92
BA
2132 );
2133 if (clonePiece) {
2134 startPiece = startPiece.cloneNode();
2135 if (this.options["rifle"]) startArray[i1][j1].style.opacity = "0";
cc2c7183 2136 if (this.options["teleport"] && this.subTurnTeleport == 2) {
41534b92
BA
2137 const pieces = this.pieces();
2138 const startCode = (dropMove ? j1 : this.getPiece(i1, j1));
2139 startPiece.classList.remove(pieces[startCode]["class"]);
2140 startPiece.classList.add(pieces[this.captured.p]["class"]);
2141 // Color: OK
2142 }
2143 container.appendChild(startPiece);
2144 }
2145 const [i2, j2] = [move.end.x, move.end.y];
2146 let startCoords;
2147 if (dropMove) {
2148 startCoords = [
2149 i1 == this.playerColor ? this.size.x : 0,
2150 this.size.y / 2 //not trying to be accurate here... (TODO?)
2151 ];
2152 }
2153 else startCoords = [i1, j1];
2154 const r = container.getBoundingClientRect();
2155 const arrival = this.getPixelPosition(i2, j2, r); //TODO: arrival on drop?
2156 let rs = [0, 0];
2157 if (dropMove) rs = this.getReserveShift(i1, j1, r);
2158 const distance =
2159 Math.sqrt((startCoords[0] - i2) ** 2 + (startCoords[1] - j2) ** 2);
2160 const maxDist = Math.sqrt((this.size.x - 1)** 2 + (this.size.y - 1) ** 2);
2161 const multFact = (distance - 1) / (maxDist - 1); //1 == minDist
2162 const duration = 0.2 + multFact * 0.3;
bc34b505 2163 const initTransform = startPiece.style.transform;
41534b92
BA
2164 startPiece.style.transform =
2165 `translate(${arrival[0] + rs[0]}px, ${arrival[1] + rs[1]}px)`;
2166 startPiece.style.transitionDuration = duration + "s";
2167 setTimeout(
2168 () => {
2169 if (clonePiece) {
2170 if (this.options["rifle"]) startArray[i1][j1].style.opacity = "1";
2171 startPiece.remove();
2172 }
bc34b505
BA
2173 else {
2174 startPiece.style.transform = initTransform;
2175 startPiece.style.transitionDuration = "0s";
2176 }
41534b92
BA
2177 callback();
2178 },
2179 duration * 1000
2180 );
2181 }
2182
2183 playReceivedMove(moves, callback) {
21e8e712
BA
2184 const launchAnimation = () => {
2185 const r =
2186 document.getElementById(this.containerId).getBoundingClientRect();
2187 const animateRec = i => {
2188 this.animate(moves[i], () => {
2189 this.playVisual(moves[i], r);
2190 this.play(moves[i]);
2191 if (i < moves.length - 1) setTimeout(() => animateRec(i+1), 300);
2192 else callback();
2193 });
2194 };
2195 animateRec(0);
2196 };
e081c5eb
BA
2197 // Delay if user wasn't focused:
2198 const checkDisplayThenAnimate = (delay) => {
21e8e712
BA
2199 if (boardContainer.style.display == "none") {
2200 alert("New move! Let's go back to game...");
2201 document.getElementById("gameInfos").style.display = "none";
2202 boardContainer.style.display = "block";
2203 setTimeout(launchAnimation, 700);
2204 }
e081c5eb 2205 else setTimeout(launchAnimation, delay || 0);
21e8e712
BA
2206 };
2207 let boardContainer = document.getElementById("boardContainer");
016306e3
BA
2208 if (document.hidden) {
2209 document.onvisibilitychange = () => {
2210 document.onvisibilitychange = undefined;
e081c5eb 2211 checkDisplayThenAnimate(700);
fd31883b 2212 };
fd31883b 2213 }
21e8e712 2214 else checkDisplayThenAnimate();
41534b92
BA
2215 }
2216
2217};