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