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