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