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