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