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