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