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