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