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