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