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