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