Add Refusal
[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;
15106e82 572 if (windowRatio <= this.size.ratio) {
41534b92
BA
573 // Limiting dimension is width:
574 cbWidth = Math.min(window.innerWidth, 767);
15106e82 575 cbHeight = cbWidth / this.size.ratio;
41534b92
BA
576 }
577 else {
578 // Limiting dimension is height:
579 cbHeight = Math.min(window.innerHeight, 767);
15106e82 580 cbWidth = cbHeight * this.size.ratio;
41534b92 581 }
1a7c0492 582 if (this.hasReserve) {
41534b92
BA
583 const sqSize = cbWidth / this.size.y;
584 // NOTE: allocate space for reserves (up/down) even if they are empty
15106e82 585 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
41534b92
BA
586 if ((window.innerHeight - cbHeight) / 2 < sqSize + 5) {
587 cbHeight = window.innerHeight - 2 * (sqSize + 5);
15106e82 588 cbWidth = cbHeight * this.size.ratio;
41534b92
BA
589 }
590 }
3c61449b
BA
591 chessboard.style.width = cbWidth + "px";
592 chessboard.style.height = cbHeight + "px";
41534b92
BA
593 // Center chessboard:
594 const spaceLeft = (window.innerWidth - cbWidth) / 2,
595 spaceTop = (window.innerHeight - cbHeight) / 2;
3c61449b
BA
596 chessboard.style.left = spaceLeft + "px";
597 chessboard.style.top = spaceTop + "px";
41534b92
BA
598 // Give sizes instead of recomputing them,
599 // because chessboard might not be drawn yet.
600 this.setupPieces({
601 width: cbWidth,
602 height: cbHeight,
603 x: spaceLeft,
604 y: spaceTop
605 });
606 }
607
608 // Get SVG board (background, no pieces)
609 getSvgChessboard() {
41534b92
BA
610 const flipped = (this.playerColor == 'b');
611 let board = `
612 <svg
613 viewBox="0 0 80 80"
535c464b 614 class="chessboard_SVG">`;
728cb1e3
BA
615 for (let i=0; i < this.size.x; i++) {
616 for (let j=0; j < this.size.y; j++) {
41534b92
BA
617 const ii = (flipped ? this.size.x - 1 - i : i);
618 const jj = (flipped ? this.size.y - 1 - j : j);
c7bf7b1b
BA
619 let classes = this.getSquareColorClass(ii, jj);
620 if (this.enlightened && !this.enlightened[ii][jj])
621 classes += " in-shadow";
41534b92 622 // NOTE: x / y reversed because coordinates system is reversed.
535c464b
BA
623 board += `
624 <rect
625 class="${classes}"
626 id="${this.coordsToId({x: ii, y: jj})}"
627 width="10"
628 height="10"
629 x="${10*j}"
630 y="${10*i}"
631 />`;
41534b92
BA
632 }
633 }
535c464b 634 board += "</svg>";
41534b92
BA
635 return board;
636 }
637
cc2c7183 638 // Generally light square bottom-right
15106e82
BA
639 getSquareColorClass(x, y) {
640 return ((x+y) % 2 == 0 ? "light-square": "dark-square");
41534b92
BA
641 }
642
643 setupPieces(r) {
644 if (this.g_pieces) {
645 // Refreshing: delete old pieces first
646 for (let i=0; i<this.size.x; i++) {
647 for (let j=0; j<this.size.y; j++) {
648 if (this.g_pieces[i][j]) {
649 this.g_pieces[i][j].remove();
650 this.g_pieces[i][j] = null;
651 }
652 }
653 }
654 }
b4ae3ff6
BA
655 else
656 this.g_pieces = ArrayFun.init(this.size.x, this.size.y, null);
3c61449b
BA
657 let chessboard =
658 document.getElementById(this.containerId).querySelector(".chessboard");
b4ae3ff6
BA
659 if (!r)
660 r = chessboard.getBoundingClientRect();
41534b92
BA
661 const pieceWidth = this.getPieceWidth(r.width);
662 for (let i=0; i < this.size.x; i++) {
663 for (let j=0; j < this.size.y; j++) {
c9ab0340 664 if (this.board[i][j] != "") {
41534b92 665 const color = this.getColor(i, j);
cc2c7183 666 const piece = this.getPiece(i, j);
41534b92 667 this.g_pieces[i][j] = document.createElement("piece");
3b641716 668 C.AddClass_es(this.g_pieces[i][j], this.pieces()[piece]["class"]);
15106e82 669 this.g_pieces[i][j].classList.add(C.GetColorClass(color));
41534b92
BA
670 this.g_pieces[i][j].style.width = pieceWidth + "px";
671 this.g_pieces[i][j].style.height = pieceWidth + "px";
9db5050a
BA
672 let [ip, jp] = this.getPixelPosition(i, j, r);
673 // Translate coordinates to use chessboard as reference:
674 this.g_pieces[i][j].style.transform =
675 `translate(${ip - r.x}px,${jp - r.y}px)`;
c9ab0340
BA
676 if (this.enlightened && !this.enlightened[i][j])
677 this.g_pieces[i][j].classList.add("hidden");
3c61449b 678 chessboard.appendChild(this.g_pieces[i][j]);
41534b92
BA
679 }
680 }
681 }
1a7c0492 682 if (this.hasReserve)
b4ae3ff6 683 this.re_drawReserve(['w', 'b'], r);
41534b92
BA
684 }
685
24872b22 686 // NOTE: assume this.reserve != null
41534b92
BA
687 re_drawReserve(colors, r) {
688 if (this.r_pieces) {
689 // Remove (old) reserve pieces
690 for (let c of colors) {
24872b22
BA
691 Object.keys(this.r_pieces[c]).forEach(p => {
692 this.r_pieces[c][p].remove();
693 delete this.r_pieces[c][p];
694 const numId = this.getReserveNumId(c, p);
695 document.getElementById(numId).remove();
41534b92 696 });
41534b92
BA
697 }
698 }
b4ae3ff6 699 else
9db5050a
BA
700 this.r_pieces = { w: {}, b: {} };
701 let container = document.getElementById(this.containerId);
b4ae3ff6 702 if (!r)
9db5050a 703 r = container.querySelector(".chessboard").getBoundingClientRect();
41534b92 704 for (let c of colors) {
24872b22
BA
705 let reservesDiv = document.getElementById("reserves_" + c);
706 if (reservesDiv)
707 reservesDiv.remove();
b4ae3ff6
BA
708 if (!this.reserve[c])
709 continue;
41534b92 710 const nbR = this.getNbReservePieces(c);
b4ae3ff6
BA
711 if (nbR == 0)
712 continue;
41534b92
BA
713 const sqResSize = this.getReserveSquareSize(r.width, nbR);
714 let ridx = 0;
715 const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5);
716 const [i0, j0] = [r.x, r.y + vShift];
717 let rcontainer = document.createElement("div");
718 rcontainer.id = "reserves_" + c;
719 rcontainer.classList.add("reserves");
720 rcontainer.style.left = i0 + "px";
721 rcontainer.style.top = j0 + "px";
1aa9054d
BA
722 // NOTE: +1 fix display bug on Firefox at least
723 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
41534b92 724 rcontainer.style.height = sqResSize + "px";
9db5050a 725 container.appendChild(rcontainer);
41534b92 726 for (let p of Object.keys(this.reserve[c])) {
b4ae3ff6
BA
727 if (this.reserve[c][p] == 0)
728 continue;
41534b92 729 let r_cell = document.createElement("div");
15106e82 730 r_cell.id = this.coordsToId({x: c, y: p});
41534b92 731 r_cell.classList.add("reserve-cell");
1aa9054d
BA
732 r_cell.style.width = sqResSize + "px";
733 r_cell.style.height = sqResSize + "px";
41534b92
BA
734 rcontainer.appendChild(r_cell);
735 let piece = document.createElement("piece");
3b641716 736 C.AddClass_es(piece, this.pieces()[p]["class"]);
15106e82 737 piece.classList.add(C.GetColorClass(c));
41534b92
BA
738 piece.style.width = "100%";
739 piece.style.height = "100%";
740 this.r_pieces[c][p] = piece;
741 r_cell.appendChild(piece);
742 let number = document.createElement("div");
743 number.textContent = this.reserve[c][p];
744 number.classList.add("reserve-num");
745 number.id = this.getReserveNumId(c, p);
746 const fontSize = "1.3em";
747 number.style.fontSize = fontSize;
748 number.style.fontSize = fontSize;
749 r_cell.appendChild(number);
750 ridx++;
751 }
752 }
753 }
754
755 updateReserve(color, piece, count) {
55a15dcb 756 if (this.options["cannibal"] && C.CannibalKings[piece])
cc2c7183 757 piece = "k"; //capturing cannibal king: back to king form
41534b92
BA
758 const oldCount = this.reserve[color][piece];
759 this.reserve[color][piece] = count;
760 // Redrawing is much easier if count==0
b4ae3ff6
BA
761 if ([oldCount, count].includes(0))
762 this.re_drawReserve([color]);
41534b92
BA
763 else {
764 const numId = this.getReserveNumId(color, piece);
765 document.getElementById(numId).textContent = count;
766 }
767 }
768
15106e82
BA
769 // Apply diff this.enlightened --> oldEnlightened on board
770 graphUpdateEnlightened() {
771 let chessboard =
772 document.getElementById(this.containerId).querySelector(".chessboard");
773 const r = chessboard.getBoundingClientRect();
774 const pieceWidth = this.getPieceWidth(r.width);
775 for (let x=0; x<this.size.x; x++) {
776 for (let y=0; y<this.size.y; y++) {
777 if (!this.enlightened[x][y] && this.oldEnlightened[x][y]) {
6997e386 778 let elt = document.getElementById(this.coordsToId({x: x, y: y}));
15106e82
BA
779 elt.classList.add("in-shadow");
780 if (this.g_pieces[x][y])
781 this.g_pieces[x][y].classList.add("hidden");
782 }
783 else if (this.enlightened[x][y] && !this.oldEnlightened[x][y]) {
6997e386 784 let elt = document.getElementById(this.coordsToId({x: x, y: y}));
15106e82
BA
785 elt.classList.remove("in-shadow");
786 if (this.g_pieces[x][y])
787 this.g_pieces[x][y].classList.remove("hidden");
788 }
789 }
790 }
791 }
792
c4e9bb92
BA
793 // Resize board: no need to destroy/recreate pieces
794 rescale(mode) {
795 let chessboard =
796 document.getElementById(this.containerId).querySelector(".chessboard");
797 const r = chessboard.getBoundingClientRect();
798 const multFact = (mode == "up" ? 1.05 : 0.95);
799 let [newWidth, newHeight] = [multFact * r.width, multFact * r.height];
535c464b 800 // Stay in window:
c4e9bb92 801 if (newWidth > window.innerWidth) {
535c464b 802 newWidth = window.innerWidth;
c4e9bb92
BA
803 newHeight = newWidth / this.size.ratio;
804 }
805 if (newHeight > window.innerHeight) {
535c464b 806 newHeight = window.innerHeight;
c4e9bb92
BA
807 newWidth = newHeight * this.size.ratio;
808 }
535c464b
BA
809 chessboard.style.width = newWidth + "px";
810 chessboard.style.height = newHeight + "px";
41534b92 811 const newX = (window.innerWidth - newWidth) / 2;
3c61449b 812 chessboard.style.left = newX + "px";
41534b92 813 const newY = (window.innerHeight - newHeight) / 2;
3c61449b 814 chessboard.style.top = newY + "px";
9db5050a 815 const newR = {x: newX, y: newY, width: newWidth, height: newHeight};
c4e9bb92 816 const pieceWidth = this.getPieceWidth(newWidth);
d621e620
BA
817 // NOTE: next "if" for variants which use squares filling
818 // instead of "physical", moving pieces
819 if (this.g_pieces) {
c4e9bb92
BA
820 for (let i=0; i < this.size.x; i++) {
821 for (let j=0; j < this.size.y; j++) {
822 if (this.g_pieces[i][j]) {
d621e620 823 // NOTE: could also use CSS transform "scale"
c4e9bb92
BA
824 this.g_pieces[i][j].style.width = pieceWidth + "px";
825 this.g_pieces[i][j].style.height = pieceWidth + "px";
826 const [ip, jp] = this.getPixelPosition(i, j, newR);
d621e620 827 // Translate coordinates to use chessboard as reference:
c4e9bb92 828 this.g_pieces[i][j].style.transform =
d621e620
BA
829 `translate(${ip - newX}px,${jp - newY}px)`;
830 }
41534b92
BA
831 }
832 }
833 }
c4e9bb92
BA
834 if (this.hasReserve)
835 this.rescaleReserve(newR);
41534b92
BA
836 }
837
838 rescaleReserve(r) {
41534b92 839 for (let c of ['w','b']) {
b4ae3ff6
BA
840 if (!this.reserve[c])
841 continue;
41534b92 842 const nbR = this.getNbReservePieces(c);
b4ae3ff6
BA
843 if (nbR == 0)
844 continue;
41534b92
BA
845 // Resize container first
846 const sqResSize = this.getReserveSquareSize(r.width, nbR);
847 const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5);
848 const [i0, j0] = [r.x, r.y + vShift];
849 let rcontainer = document.getElementById("reserves_" + c);
850 rcontainer.style.left = i0 + "px";
851 rcontainer.style.top = j0 + "px";
1aa9054d 852 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
41534b92
BA
853 rcontainer.style.height = sqResSize + "px";
854 // And then reserve cells:
855 const rpieceWidth = this.getReserveSquareSize(r.width, nbR);
856 Object.keys(this.reserve[c]).forEach(p => {
b4ae3ff6
BA
857 if (this.reserve[c][p] == 0)
858 return;
15106e82 859 let r_cell = document.getElementById(this.coordsToId({x: c, y: p}));
1aa9054d
BA
860 r_cell.style.width = sqResSize + "px";
861 r_cell.style.height = sqResSize + "px";
41534b92
BA
862 });
863 }
864 }
865
9db5050a 866 // Return the absolute pixel coordinates given current position.
41534b92
BA
867 // Our coordinate system differs from CSS one (x <--> y).
868 // We return here the CSS coordinates (more useful).
869 getPixelPosition(i, j, r) {
b4ae3ff6
BA
870 if (i < 0 || j < 0)
871 return [0, 0]; //piece vanishes
15106e82
BA
872 let x, y;
873 if (typeof i == "string") {
874 // Reserves: need to know the rank of piece
875 const nbR = this.getNbReservePieces(i);
876 const rsqSize = this.getReserveSquareSize(r.width, nbR);
877 x = this.getRankInReserve(i, j) * rsqSize;
878 y = (this.playerColor == i ? y = r.height + 5 : - 5 - rsqSize);
879 }
880 else {
881 const sqSize = r.width / this.size.y;
882 const flipped = (this.playerColor == 'b');
883 x = (flipped ? this.size.y - 1 - j : j) * sqSize;
884 y = (flipped ? this.size.x - 1 - i : i) * sqSize;
885 }
9db5050a 886 return [r.x + x, r.y + y];
41534b92
BA
887 }
888
889 initMouseEvents() {
9db5050a
BA
890 let container = document.getElementById(this.containerId);
891 let chessboard = container.querySelector(".chessboard");
41534b92
BA
892
893 const getOffset = e => {
3c61449b
BA
894 if (e.clientX)
895 // Mouse
896 return {x: e.clientX, y: e.clientY};
41534b92
BA
897 let touchLocation = null;
898 if (e.targetTouches && e.targetTouches.length >= 1)
899 // Touch screen, dragstart
900 touchLocation = e.targetTouches[0];
901 else if (e.changedTouches && e.changedTouches.length >= 1)
902 // Touch screen, dragend
903 touchLocation = e.changedTouches[0];
904 if (touchLocation)
11625344 905 return {x: touchLocation.clientX, y: touchLocation.clientY};
57b8015b 906 return {x: 0, y: 0}; //shouldn't reach here =)
41534b92
BA
907 }
908
909 const centerOnCursor = (piece, e) => {
15106e82 910 const centerShift = this.getPieceWidth(r.width) / 2;
41534b92 911 const offset = getOffset(e);
9db5050a
BA
912 piece.style.left = (offset.x - centerShift) + "px";
913 piece.style.top = (offset.y - centerShift) + "px";
41534b92
BA
914 }
915
916 let start = null,
917 r = null,
918 startPiece, curPiece = null,
15106e82 919 pieceWidth;
41534b92 920 const mousedown = (e) => {
cb17fed8 921 // Disable zoom on smartphones:
b4ae3ff6
BA
922 if (e.touches && e.touches.length > 1)
923 e.preventDefault();
3c61449b 924 r = chessboard.getBoundingClientRect();
15106e82
BA
925 pieceWidth = this.getPieceWidth(r.width);
926 const cd = this.idToCoords(e.target.id);
927 if (cd) {
928 const move = this.doClick(cd);
b4ae3ff6
BA
929 if (move)
930 this.playPlusVisual(move);
41534b92 931 else {
15106e82
BA
932 const [x, y] = Object.values(cd);
933 if (typeof x != "number")
934 startPiece = this.r_pieces[x][y];
935 else
936 startPiece = this.g_pieces[x][y];
937 if (startPiece && this.canIplay(x, y)) {
41534b92 938 e.preventDefault();
15106e82 939 start = cd;
41534b92
BA
940 curPiece = startPiece.cloneNode();
941 curPiece.style.transform = "none";
942 curPiece.style.zIndex = 5;
15106e82
BA
943 curPiece.style.width = pieceWidth + "px";
944 curPiece.style.height = pieceWidth + "px";
41534b92 945 centerOnCursor(curPiece, e);
9db5050a 946 container.appendChild(curPiece);
41534b92 947 startPiece.style.opacity = "0.4";
3c61449b 948 chessboard.style.cursor = "none";
41534b92
BA
949 }
950 }
951 }
952 };
953
954 const mousemove = (e) => {
955 if (start) {
956 e.preventDefault();
957 centerOnCursor(curPiece, e);
958 }
11625344
BA
959 else if (e.changedTouches && e.changedTouches.length >= 1)
960 // Attempt to prevent horizontal swipe...
961 e.preventDefault();
41534b92
BA
962 };
963
964 const mouseup = (e) => {
b4ae3ff6
BA
965 if (!start)
966 return;
41534b92
BA
967 const [x, y] = [start.x, start.y];
968 start = null;
969 e.preventDefault();
3c61449b 970 chessboard.style.cursor = "pointer";
41534b92
BA
971 startPiece.style.opacity = "1";
972 const offset = getOffset(e);
973 const landingElt = document.elementFromPoint(offset.x, offset.y);
15106e82
BA
974 const cd =
975 (landingElt ? this.idToCoords(landingElt.id) : undefined);
976 if (cd) {
41534b92
BA
977 // NOTE: clearly suboptimal, but much easier, and not a big deal.
978 const potentialMoves = this.getPotentialMovesFrom([x, y])
15106e82 979 .filter(m => m.end.x == cd.x && m.end.y == cd.y);
41534b92 980 const moves = this.filterValid(potentialMoves);
b4ae3ff6
BA
981 if (moves.length >= 2)
982 this.showChoices(moves, r);
983 else if (moves.length == 1)
984 this.playPlusVisual(moves[0], r);
41534b92
BA
985 }
986 curPiece.remove();
987 };
988
989 if ('onmousedown' in window) {
990 document.addEventListener("mousedown", mousedown);
991 document.addEventListener("mousemove", mousemove);
992 document.addEventListener("mouseup", mouseup);
437dfd42
BA
993 document.addEventListener("wheel",
994 (e) => this.rescale(e.deltaY < 0 ? "up" : "down"));
41534b92
BA
995 }
996 if ('ontouchstart' in window) {
cb17fed8
BA
997 // https://stackoverflow.com/a/42509310/12660887
998 document.addEventListener("touchstart", mousedown, {passive: false});
999 document.addEventListener("touchmove", mousemove, {passive: false});
1000 document.addEventListener("touchend", mouseup, {passive: false});
41534b92 1001 }
11625344 1002 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
41534b92
BA
1003 }
1004
1005 showChoices(moves, r) {
1006 let container = document.getElementById(this.containerId);
3c61449b 1007 let chessboard = container.querySelector(".chessboard");
41534b92
BA
1008 let choices = document.createElement("div");
1009 choices.id = "choices";
a2bb7e06
BA
1010 if (!r)
1011 r = chessboard.getBoundingClientRect();
41534b92
BA
1012 choices.style.width = r.width + "px";
1013 choices.style.height = r.height + "px";
1014 choices.style.left = r.x + "px";
1015 choices.style.top = r.y + "px";
3c61449b
BA
1016 chessboard.style.opacity = "0.5";
1017 container.appendChild(choices);
15106e82 1018 const squareWidth = r.width / this.size.y;
41534b92
BA
1019 const firstUpLeft = (r.width - (moves.length * squareWidth)) / 2;
1020 const firstUpTop = (r.height - squareWidth) / 2;
1021 const color = moves[0].appear[0].c;
1022 const callback = (m) => {
3c61449b
BA
1023 chessboard.style.opacity = "1";
1024 container.removeChild(choices);
41534b92
BA
1025 this.playPlusVisual(m, r);
1026 }
1027 for (let i=0; i < moves.length; i++) {
1028 let choice = document.createElement("div");
1029 choice.classList.add("choice");
1030 choice.style.width = squareWidth + "px";
1031 choice.style.height = squareWidth + "px";
1032 choice.style.left = (firstUpLeft + i * squareWidth) + "px";
1033 choice.style.top = firstUpTop + "px";
1034 choice.style.backgroundColor = "lightyellow";
1035 choice.onclick = () => callback(moves[i]);
1036 const piece = document.createElement("piece");
3b641716
BA
1037 const cdisp = moves[i].choice || moves[i].appear[0].p;
1038 C.AddClass_es(piece, this.pieces()[cdisp]["class"]);
15106e82 1039 piece.classList.add(C.GetColorClass(color));
41534b92
BA
1040 piece.style.width = "100%";
1041 piece.style.height = "100%";
1042 choice.appendChild(piece);
1043 choices.appendChild(choice);
1044 }
1045 }
1046
1047 //////////////
1048 // BASIC UTILS
1049
1050 get size() {
15106e82
BA
1051 return {
1052 x: 8,
1053 y: 8,
1054 ratio: 1 //for rectangular board = y / x
1055 };
41534b92
BA
1056 }
1057
1058 // Color of thing on square (i,j). 'undefined' if square is empty
1059 getColor(i, j) {
15106e82
BA
1060 if (typeof i == "string")
1061 return i; //reserves
41534b92
BA
1062 return this.board[i][j].charAt(0);
1063 }
1064
15106e82 1065 static GetColorClass(c) {
bc2bc396
BA
1066 if (c == 'w')
1067 return "white";
1068 if (c == 'b')
1069 return "black";
24872b22 1070 return "other-color"; //unidentified color
15106e82
BA
1071 }
1072
cc2c7183 1073 // Assume square i,j isn't empty
41534b92 1074 getPiece(i, j) {
15106e82
BA
1075 if (typeof j == "string")
1076 return j; //reserves
41534b92
BA
1077 return this.board[i][j].charAt(1);
1078 }
1079
cc2c7183
BA
1080 // Piece type on square (i,j)
1081 getPieceType(i, j) {
6997e386 1082 const p = this.getPiece(i, j);
cc2c7183
BA
1083 return C.CannibalKings[p] || p; //a cannibal king move as...
1084 }
1085
41534b92
BA
1086 // Get opponent color
1087 static GetOppCol(color) {
1088 return (color == "w" ? "b" : "w");
1089 }
1090
c9ab0340 1091 // Can thing on square1 capture (no return) thing on square2?
41534b92 1092 canTake([x1, y1], [x2, y2]) {
c9ab0340 1093 return (this.getColor(x1, y1) !== this.getColor(x2, y2));
41534b92
BA
1094 }
1095
1096 // Is (x,y) on the chessboard?
1097 onBoard(x, y) {
b99ce1fb
BA
1098 return (x >= 0 && x < this.size.x &&
1099 y >= 0 && y < this.size.y);
41534b92
BA
1100 }
1101
15106e82 1102 // Am I allowed to move thing at square x,y ?
41534b92 1103 canIplay(x, y) {
0c44c676 1104 return (this.playerColor == this.turn && this.getColor(x, y) == this.turn);
41534b92
BA
1105 }
1106
1107 ////////////////////////
1108 // PIECES SPECIFICATIONS
1109
c9ab0340 1110 pieces(color, x, y) {
41534b92 1111 const pawnShift = (color == "w" ? -1 : 1);
9db5050a
BA
1112 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1113 const initRank = ((color == 'w' && x >= 6) || (color == 'b' && x <= 1));
41534b92
BA
1114 return {
1115 'p': {
1116 "class": "pawn",
c9ab0340
BA
1117 moves: [
1118 {
1119 steps: [[pawnShift, 0]],
1120 range: (initRank ? 2 : 1)
1121 }
1122 ],
1123 attack: [
1124 {
1125 steps: [[pawnShift, 1], [pawnShift, -1]],
1126 range: 1
1127 }
1128 ]
41534b92
BA
1129 },
1130 // rook
1131 'r': {
1132 "class": "rook",
c9ab0340
BA
1133 moves: [
1134 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1135 ]
41534b92
BA
1136 },
1137 // knight
1138 'n': {
1139 "class": "knight",
c9ab0340
BA
1140 moves: [
1141 {
1142 steps: [
1143 [1, 2], [1, -2], [-1, 2], [-1, -2],
1144 [2, 1], [-2, 1], [2, -1], [-2, -1]
1145 ],
1146 range: 1
1147 }
1148 ]
41534b92
BA
1149 },
1150 // bishop
1151 'b': {
1152 "class": "bishop",
c9ab0340
BA
1153 moves: [
1154 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1155 ]
41534b92
BA
1156 },
1157 // queen
1158 'q': {
1159 "class": "queen",
c9ab0340
BA
1160 moves: [
1161 {
1162 steps: [
1163 [0, 1], [0, -1], [1, 0], [-1, 0],
1164 [1, 1], [1, -1], [-1, 1], [-1, -1]
1165 ]
1166 }
41534b92
BA
1167 ]
1168 },
1169 // king
1170 'k': {
1171 "class": "king",
c9ab0340
BA
1172 moves: [
1173 {
1174 steps: [
1175 [0, 1], [0, -1], [1, 0], [-1, 0],
1176 [1, 1], [1, -1], [-1, 1], [-1, -1]
1177 ],
1178 range: 1
1179 }
1180 ]
cc2c7183
BA
1181 },
1182 // Cannibal kings:
c9ab0340
BA
1183 '!': {"class": "king-pawn", moveas: "p"},
1184 '#': {"class": "king-rook", moveas: "r"},
1185 '$': {"class": "king-knight", moveas: "n"},
1186 '%': {"class": "king-bishop", moveas: "b"},
1187 '*': {"class": "king-queen", moveas: "q"}
41534b92
BA
1188 };
1189 }
1190
41534b92
BA
1191 ////////////////////
1192 // MOVES GENERATION
1193
adf7c659
BA
1194 // For Cylinder: get Y coordinate
1195 getY(y) {
b4ae3ff6
BA
1196 if (!this.options["cylinder"])
1197 return y;
41534b92 1198 let res = y % this.size.y;
b4ae3ff6 1199 if (res < 0)
adf7c659 1200 res += this.size.y;
41534b92
BA
1201 return res;
1202 }
1203
1204 // Stop at the first capture found
1205 atLeastOneCapture(color) {
1206 color = color || this.turn;
cc2c7183 1207 const oppCol = C.GetOppCol(color);
41534b92
BA
1208 for (let i = 0; i < this.size.x; i++) {
1209 for (let j = 0; j < this.size.y; j++) {
1210 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
c9ab0340
BA
1211 const allSpecs = this.pieces(color, i, j)
1212 let specs = allSpecs[this.getPieceType(i, j)];
1213 const attacks = specs.attack || specs.moves;
1214 for (let a of attacks) {
1215 outerLoop: for (let step of a.steps) {
d262cff4 1216 let [ii, jj] = [i + step[0], this.getY(j + step[1])];
c9ab0340
BA
1217 let stepCounter = 1;
1218 while (this.onBoard(ii, jj) && this.board[ii][jj] == "") {
1219 if (a.range <= stepCounter++)
1220 continue outerLoop;
1221 ii += step[0];
d262cff4 1222 jj = this.getY(jj + step[1]);
c9ab0340
BA
1223 }
1224 if (
1225 this.onBoard(ii, jj) &&
1226 this.getColor(ii, jj) == oppCol &&
1227 this.filterValid(
1228 [this.getBasicMove([i, j], [ii, jj])]
1229 ).length >= 1
1230 ) {
1231 return true;
1232 }
41534b92
BA
1233 }
1234 }
1235 }
1236 }
1237 }
1238 return false;
1239 }
1240
1241 getDropMovesFrom([c, p]) {
1242 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1a7c0492 1243 // (but not necessarily otherwise: atLeastOneMove() etc)
b4ae3ff6
BA
1244 if (this.reserve[c][p] == 0)
1245 return [];
41534b92
BA
1246 let moves = [];
1247 for (let i=0; i<this.size.x; i++) {
1248 for (let j=0; j<this.size.y; j++) {
41534b92
BA
1249 if (
1250 this.board[i][j] == "" &&
c9ab0340 1251 (!this.enlightened || this.enlightened[i][j]) &&
41534b92 1252 (
cc2c7183 1253 p != "p" ||
41534b92
BA
1254 (c == 'w' && i < this.size.x - 1) ||
1255 (c == 'b' && i > 0)
1256 )
1257 ) {
1258 moves.push(
1259 new Move({
1260 start: {x: c, y: p},
1261 end: {x: i, y: j},
1262 appear: [new PiPo({x: i, y: j, c: c, p: p})],
1263 vanish: []
1264 })
1265 );
1266 }
1267 }
1268 }
1269 return moves;
1270 }
1271
1272 // All possible moves from selected square
c7bf7b1b 1273 getPotentialMovesFrom(sq, color) {
8b301184
BA
1274 if (this.subTurnTeleport == 2)
1275 return [];
b4ae3ff6
BA
1276 if (typeof sq[0] == "string")
1277 return this.getDropMovesFrom(sq);
57b8015b 1278 if (this.isImmobilized(sq))
b4ae3ff6 1279 return [];
cc2c7183 1280 const piece = this.getPieceType(sq[0], sq[1]);
c9ab0340
BA
1281 let moves = this.getPotentialMovesOf(piece, sq);
1282 if (
1283 piece == "p" &&
1284 this.hasEnpassant &&
1285 this.epSquare
1286 ) {
1287 Array.prototype.push.apply(moves, this.getEnpassantCaptures(sq));
1288 }
41534b92 1289 if (
cc2c7183 1290 piece == "k" &&
41534b92
BA
1291 this.hasCastle &&
1292 this.castleFlags[color || this.turn].some(v => v < this.size.y)
1293 ) {
1294 Array.prototype.push.apply(moves, this.getCastleMoves(sq));
1295 }
1296 return this.postProcessPotentialMoves(moves);
1297 }
1298
1299 postProcessPotentialMoves(moves) {
b4ae3ff6
BA
1300 if (moves.length == 0)
1301 return [];
41534b92 1302 const color = this.getColor(moves[0].start.x, moves[0].start.y);
cc2c7183 1303 const oppCol = C.GetOppCol(color);
41534b92 1304
57b8015b
BA
1305 if (this.options["capture"] && this.atLeastOneCapture())
1306 moves = this.capturePostProcess(moves, oppCol);
41534b92 1307
57b8015b
BA
1308 if (this.options["atomic"])
1309 this.atomicPostProcess(moves, oppCol);
cc2c7183 1310
c9ab0340
BA
1311 if (
1312 moves.length > 0 &&
1313 this.getPieceType(moves[0].start.x, moves[0].start.y) == "p"
1314 ) {
57b8015b 1315 this.pawnPostProcess(moves, color, oppCol);
c9ab0340
BA
1316 }
1317
cc2c7183
BA
1318 if (
1319 this.options["cannibal"] &&
57b8015b 1320 this.options["rifle"]
cc2c7183
BA
1321 ) {
1322 // In this case a rifle-capture from last rank may promote a pawn
9db5050a 1323 this.riflePromotePostProcess(moves, color);
57b8015b
BA
1324 }
1325
1326 return moves;
1327 }
1328
1329 capturePostProcess(moves, oppCol) {
1330 // Filter out non-capturing moves (not using m.vanish because of
1331 // self captures of Recycle and Teleport).
1332 return moves.filter(m => {
1333 return (
1334 this.board[m.end.x][m.end.y] != "" &&
1335 this.getColor(m.end.x, m.end.y) == oppCol
1336 );
1337 });
1338 }
1339
1340 atomicPostProcess(moves, oppCol) {
1341 moves.forEach(m => {
1342 if (
1343 this.board[m.end.x][m.end.y] != "" &&
1344 this.getColor(m.end.x, m.end.y) == oppCol
1345 ) {
1346 // Explosion!
1347 let steps = [
1348 [-1, -1],
1349 [-1, 0],
1350 [-1, 1],
1351 [0, -1],
1352 [0, 1],
1353 [1, -1],
1354 [1, 0],
1355 [1, 1]
1356 ];
1357 for (let step of steps) {
1358 let x = m.end.x + step[0];
d262cff4 1359 let y = this.getY(m.end.y + step[1]);
57b8015b
BA
1360 if (
1361 this.onBoard(x, y) &&
1362 this.board[x][y] != "" &&
1363 this.getPieceType(x, y) != "p"
1364 ) {
1365 m.vanish.push(
1366 new PiPo({
1367 p: this.getPiece(x, y),
1368 c: this.getColor(x, y),
1369 x: x,
1370 y: y
1371 })
1372 );
1373 }
1374 }
1375 if (!this.options["rifle"])
0c44c676 1376 m.appear.pop(); //nothing appears
57b8015b
BA
1377 }
1378 });
1379 }
1380
1381 pawnPostProcess(moves, color, oppCol) {
1382 let moreMoves = [];
1383 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1384 const initPiece = this.getPiece(moves[0].start.x, moves[0].start.y);
1385 moves.forEach(m => {
57b8015b
BA
1386 const [x1, y1] = [m.start.x, m.start.y];
1387 const [x2, y2] = [m.end.x, m.end.y];
1388 const promotionOk = (
1389 x2 == lastRank &&
1390 (!this.options["rifle"] || this.board[x2][y2] == "")
1391 );
1392 if (!promotionOk)
1393 return; //nothing to do
8cc2f6d0
BA
1394 if (this.options["pawnfall"]) {
1395 m.appear.shift();
8cc2f6d0
BA
1396 return;
1397 }
99ea2453
BA
1398 let finalPieces = ["p"];
1399 if (
1400 this.options["cannibal"] &&
1401 this.board[x2][y2] != "" &&
1402 this.getColor(x2, y2) == oppCol
1403 ) {
1404 finalPieces = [this.getPieceType(x2, y2)];
1405 }
1406 else
1407 finalPieces = this.pawnPromotions;
57b8015b
BA
1408 m.appear[0].p = finalPieces[0];
1409 if (initPiece == "!") //cannibal king-pawn
1410 m.appear[0].p = C.CannibalKingCode[finalPieces[0]];
1411 for (let i=1; i<finalPieces.length; i++) {
1412 const piece = finalPieces[i];
99ea2453
BA
1413 const tr = {
1414 c: color,
1415 p: (initPiece != "!" ? piece : C.CannibalKingCode[piece])
1416 };
57b8015b 1417 let newMove = this.getBasicMove([x1, y1], [x2, y2], tr);
57b8015b
BA
1418 moreMoves.push(newMove);
1419 }
1420 });
1421 Array.prototype.push.apply(moves, moreMoves);
1422 }
cc2c7183 1423
9db5050a 1424 riflePromotePostProcess(moves, color) {
57b8015b
BA
1425 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1426 let newMoves = [];
1427 moves.forEach(m => {
1428 if (
1429 m.start.x == lastRank &&
1430 m.appear.length >= 1 &&
1431 m.appear[0].p == "p" &&
1432 m.appear[0].x == m.start.x &&
1433 m.appear[0].y == m.start.y
1434 ) {
57b8015b
BA
1435 m.appear[0].p = this.pawnPromotions[0];
1436 for (let i=1; i<this.pawnPromotions.length; i++) {
1437 let newMv = JSON.parse(JSON.stringify(m));
1438 newMv.appear[0].p = this.pawnSpecs.promotions[i];
1439 newMoves.push(newMv);
1440 }
1441 }
1442 });
1443 Array.prototype.push.apply(moves, newMoves);
41534b92
BA
1444 }
1445
b99ce1fb 1446 // NOTE: using special symbols to not interfere with variants' pieces codes
cc2c7183
BA
1447 static get CannibalKings() {
1448 return {
b99ce1fb
BA
1449 "!": "p",
1450 "#": "r",
1451 "$": "n",
1452 "%": "b",
6997e386
BA
1453 "*": "q",
1454 "k": "k"
cc2c7183
BA
1455 };
1456 }
1457
1458 static get CannibalKingCode() {
1459 return {
b99ce1fb
BA
1460 "p": "!",
1461 "r": "#",
1462 "n": "$",
1463 "b": "%",
1464 "q": "*",
cc2c7183
BA
1465 "k": "k"
1466 };
1467 }
1468
1469 isKing(symbol) {
6997e386 1470 return !!C.CannibalKings[symbol];
cc2c7183
BA
1471 }
1472
41534b92
BA
1473 // For Madrasi:
1474 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1475 isImmobilized([x, y]) {
57b8015b
BA
1476 if (!this.options["madrasi"])
1477 return false;
41534b92 1478 const color = this.getColor(x, y);
cc2c7183 1479 const oppCol = C.GetOppCol(color);
c9ab0340 1480 const piece = this.getPieceType(x, y); //ok not cannibal king
57b8015b 1481 const stepSpec = this.pieces(color, x, y)[piece];
c9ab0340
BA
1482 const attacks = stepSpec.attack || stepSpec.moves;
1483 for (let a of attacks) {
1484 outerLoop: for (let step of a.steps) {
1485 let [i, j] = [x + step[0], y + step[1]];
1486 let stepCounter = 1;
1487 while (this.onBoard(i, j) && this.board[i][j] == "") {
1488 if (a.range <= stepCounter++)
1489 continue outerLoop;
1490 i += step[0];
d262cff4 1491 j = this.getY(j + step[1]);
c9ab0340
BA
1492 }
1493 if (
1494 this.onBoard(i, j) &&
1495 this.getColor(i, j) == oppCol &&
1496 this.getPieceType(i, j) == piece
1497 ) {
1498 return true;
1499 }
41534b92
BA
1500 }
1501 }
1502 return false;
1503 }
1504
3b641716
BA
1505 canStepOver(i, j) {
1506 // In some variants, objects on boards don't stop movement (Chakart)
1507 return this.board[i][j] == "";
1508 }
1509
41534b92
BA
1510 // Generic method to find possible moves of "sliding or jumping" pieces
1511 getPotentialMovesOf(piece, [x, y]) {
1512 const color = this.getColor(x, y);
c9ab0340 1513 const stepSpec = this.pieces(color, x, y)[piece];
41534b92 1514 let moves = [];
adf7c659
BA
1515 // Next 3 for Cylinder mode:
1516 let explored = {};
1517 let segments = [];
1518 let segStart = [];
1519
1520 const addMove = (start, end) => {
1521 let newMove = this.getBasicMove(start, end);
1522 if (segments.length > 0) {
1523 newMove.segments = JSON.parse(JSON.stringify(segments));
1524 newMove.segments.push([[segStart[0], segStart[1]], [end[0], end[1]]]);
1525 }
1526 moves.push(newMove);
1527 };
c9ab0340
BA
1528
1529 const findAddMoves = (type, stepArray) => {
1530 for (let s of stepArray) {
1531 outerLoop: for (let step of s.steps) {
adf7c659
BA
1532 segments = [];
1533 segStart = [x, y];
d262cff4
BA
1534 let [i, j] = [x, y];
1535 let stepCounter = 0;
1536 while (
1537 this.onBoard(i, j) &&
3b641716 1538 (this.canStepOver(i, j) || (i == x && j == y))
d262cff4
BA
1539 ) {
1540 if (
1541 type != "attack" &&
1542 !explored[i + "." + j] &&
1543 (i != x || j != y)
1544 ) {
c9ab0340 1545 explored[i + "." + j] = true;
adf7c659 1546 addMove([x, y], [i, j]);
c9ab0340
BA
1547 }
1548 if (s.range <= stepCounter++)
1549 continue outerLoop;
d262cff4 1550 const oldIJ = [i, j];
c9ab0340 1551 i += step[0];
adf7c659
BA
1552 j = this.getY(j + step[1]);
1553 if (Math.abs(j - oldIJ[1]) > 1) {
d262cff4 1554 // Boundary between segments (cylinder mode)
adf7c659
BA
1555 segments.push([[segStart[0], segStart[1]], oldIJ]);
1556 segStart = [i, j];
d262cff4 1557 }
c9ab0340
BA
1558 }
1559 if (!this.onBoard(i, j))
1560 continue;
1561 const pieceIJ = this.getPieceType(i, j);
1562 if (
1563 type != "moveonly" &&
1564 !explored[i + "." + j] &&
1565 (
1566 !this.options["zen"] ||
1567 pieceIJ == "k"
1568 ) &&
1569 (
1570 this.canTake([x, y], [i, j]) ||
1571 (
1572 (this.options["recycle"] || this.options["teleport"]) &&
1573 pieceIJ != "k"
1574 )
1575 )
1576 ) {
1577 explored[i + "." + j] = true;
adf7c659 1578 addMove([x, y], [i, j]);
c9ab0340
BA
1579 }
1580 }
41534b92 1581 }
c9ab0340
BA
1582 };
1583
1584 const specialAttack = !!stepSpec.attack;
1585 if (specialAttack)
1586 findAddMoves("attack", stepSpec.attack);
1587 findAddMoves(specialAttack ? "moveonly" : "all", stepSpec.moves);
082e639a
BA
1588 if (this.options["zen"]) {
1589 Array.prototype.push.apply(moves,
1590 this.findCapturesOn([x, y], {zen: true}));
1591 }
41534b92
BA
1592 return moves;
1593 }
1594
082e639a
BA
1595 // Search for enemy (or not) pieces attacking [x, y]
1596 findCapturesOn([x, y], args) {
41534b92 1597 let moves = [];
082e639a
BA
1598 if (!args.oppCol)
1599 args.oppCol = C.GetOppCol(this.getColor(x, y) || this.turn);
c9ab0340
BA
1600 for (let i=0; i<this.size.x; i++) {
1601 for (let j=0; j<this.size.y; j++) {
57b8015b
BA
1602 if (
1603 this.board[i][j] != "" &&
082e639a 1604 this.getColor(i, j) == args.oppCol &&
57b8015b
BA
1605 !this.isImmobilized([i, j])
1606 ) {
082e639a 1607 if (args.zen && this.isKing(this.getPiece(i, j)))
c9ab0340 1608 continue; //king not captured in this way
082e639a
BA
1609 const stepSpec =
1610 this.pieces(args.oppCol, i, j)[this.getPieceType(i, j)];
c9ab0340
BA
1611 const attacks = stepSpec.attack || stepSpec.moves;
1612 for (let a of attacks) {
1613 for (let s of a.steps) {
1614 // Quick check: if step isn't compatible, don't even try
57b8015b 1615 if (!C.CompatibleStep([i, j], [x, y], s, a.range))
c9ab0340
BA
1616 continue;
1617 // Finally verify that nothing stand in-between
d262cff4 1618 let [ii, jj] = [i + s[0], this.getY(j + s[1])];
c9ab0340 1619 let stepCounter = 1;
082e639a
BA
1620 while (
1621 this.onBoard(ii, jj) &&
1622 this.board[ii][jj] == "" &&
1623 (ii != x || jj != y) //condition to attack empty squares too
1624 ) {
c9ab0340 1625 ii += s[0];
d262cff4 1626 jj = this.getY(jj + s[1]);
c9ab0340
BA
1627 }
1628 if (ii == x && jj == y) {
082e639a
BA
1629 if (args.zen)
1630 // Reverse capture:
1631 moves.push(this.getBasicMove([x, y], [i, j]));
1632 else
1633 moves.push(this.getBasicMove([i, j], [x, y]));
1634 if (args.one)
c9ab0340
BA
1635 return moves; //test for underCheck
1636 }
1637 }
1638 }
41534b92 1639 }
c9ab0340
BA
1640 }
1641 }
41534b92
BA
1642 return moves;
1643 }
1644
57b8015b
BA
1645 static CompatibleStep([x1, y1], [x2, y2], step, range) {
1646 const rx = (x2 - x1) / step[0],
1647 ry = (y2 - y1) / step[1];
1648 if (
1649 (!Number.isFinite(rx) && !Number.isNaN(rx)) ||
1650 (!Number.isFinite(ry) && !Number.isNaN(ry))
1651 ) {
1652 return false;
1653 }
1654 let distance = (Number.isNaN(rx) ? ry : rx);
1655 // TODO: 1e-7 here is totally arbitrary
1656 if (Math.abs(distance - Math.round(distance)) > 1e-7)
1657 return false;
1658 distance = Math.round(distance); //in case of (numerical...)
1659 if (range < distance)
1660 return false;
1661 return true;
1662 }
1663
41534b92
BA
1664 // Build a regular move from its initial and destination squares.
1665 // tr: transformation
1666 getBasicMove([sx, sy], [ex, ey], tr) {
1667 const initColor = this.getColor(sx, sy);
cc2c7183 1668 const initPiece = this.getPiece(sx, sy);
41534b92
BA
1669 const destColor = (this.board[ex][ey] != "" ? this.getColor(ex, ey) : "");
1670 let mv = new Move({
1671 appear: [],
1672 vanish: [],
15106e82
BA
1673 start: {x: sx, y: sy},
1674 end: {x: ex, y: ey}
41534b92
BA
1675 });
1676 if (
1677 !this.options["rifle"] ||
1678 this.board[ex][ey] == "" ||
1679 destColor == initColor //Recycle, Teleport
1680 ) {
1681 mv.appear = [
1682 new PiPo({
1683 x: ex,
1684 y: ey,
1685 c: !!tr ? tr.c : initColor,
1686 p: !!tr ? tr.p : initPiece
1687 })
1688 ];
1689 mv.vanish = [
1690 new PiPo({
1691 x: sx,
1692 y: sy,
1693 c: initColor,
1694 p: initPiece
1695 })
1696 ];
1697 }
1698 if (this.board[ex][ey] != "") {
1699 mv.vanish.push(
1700 new PiPo({
1701 x: ex,
1702 y: ey,
1703 c: this.getColor(ex, ey),
cc2c7183 1704 p: this.getPiece(ex, ey)
41534b92
BA
1705 })
1706 );
41534b92
BA
1707 if (this.options["cannibal"] && destColor != initColor) {
1708 const lastIdx = mv.vanish.length - 1;
cc2c7183
BA
1709 let trPiece = mv.vanish[lastIdx].p;
1710 if (this.isKing(this.getPiece(sx, sy)))
1711 trPiece = C.CannibalKingCode[trPiece];
b4ae3ff6
BA
1712 if (mv.appear.length >= 1)
1713 mv.appear[0].p = trPiece;
41534b92
BA
1714 else if (this.options["rifle"]) {
1715 mv.appear.unshift(
1716 new PiPo({
1717 x: sx,
1718 y: sy,
1719 c: initColor,
cc2c7183 1720 p: trPiece
41534b92
BA
1721 })
1722 );
1723 mv.vanish.unshift(
1724 new PiPo({
1725 x: sx,
1726 y: sy,
1727 c: initColor,
1728 p: initPiece
1729 })
1730 );
1731 }
1732 }
1733 }
1734 return mv;
1735 }
1736
1737 // En-passant square, if any
1738 getEpSquare(moveOrSquare) {
1739 if (typeof moveOrSquare === "string") {
1740 const square = moveOrSquare;
b4ae3ff6
BA
1741 if (square == "-")
1742 return undefined;
cc2c7183 1743 return C.SquareToCoords(square);
41534b92
BA
1744 }
1745 // Argument is a move:
1746 const move = moveOrSquare;
1747 const s = move.start,
1748 e = move.end;
1749 if (
1750 s.y == e.y &&
1751 Math.abs(s.x - e.x) == 2 &&
1752 // Next conditions for variants like Atomic or Rifle, Recycle...
cc2c7183
BA
1753 (move.appear.length > 0 && move.appear[0].p == "p") &&
1754 (move.vanish.length > 0 && move.vanish[0].p == "p")
41534b92
BA
1755 ) {
1756 return {
1757 x: (s.x + e.x) / 2,
1758 y: s.y
1759 };
1760 }
1761 return undefined; //default
1762 }
1763
1764 // Special case of en-passant captures: treated separately
c9ab0340 1765 getEnpassantCaptures([x, y]) {
41534b92 1766 const color = this.getColor(x, y);
c9ab0340 1767 const shiftX = (color == 'w' ? -1 : 1);
cc2c7183 1768 const oppCol = C.GetOppCol(color);
41534b92
BA
1769 let enpassantMove = null;
1770 if (
1771 !!this.epSquare &&
1772 this.epSquare.x == x + shiftX &&
d262cff4 1773 Math.abs(this.getY(this.epSquare.y - y)) == 1 &&
41534b92
BA
1774 this.getColor(x, this.epSquare.y) == oppCol //Doublemove guard...
1775 ) {
1776 const [epx, epy] = [this.epSquare.x, this.epSquare.y];
1777 this.board[epx][epy] = oppCol + "p";
1778 enpassantMove = this.getBasicMove([x, y], [epx, epy]);
1779 this.board[epx][epy] = "";
1780 const lastIdx = enpassantMove.vanish.length - 1; //think Rifle
1781 enpassantMove.vanish[lastIdx].x = x;
1782 }
1783 return !!enpassantMove ? [enpassantMove] : [];
1784 }
1785
41534b92
BA
1786 // "castleInCheck" arg to let some variants castle under check
1787 getCastleMoves([x, y], finalSquares, castleInCheck, castleWith) {
1788 const c = this.getColor(x, y);
1789
1790 // Castling ?
cc2c7183 1791 const oppCol = C.GetOppCol(c);
41534b92
BA
1792 let moves = [];
1793 // King, then rook:
1794 finalSquares =
1795 finalSquares || [ [2, 3], [this.size.y - 2, this.size.y - 3] ];
cc2c7183 1796 const castlingKing = this.getPiece(x, y);
41534b92
BA
1797 castlingCheck: for (
1798 let castleSide = 0;
1799 castleSide < 2;
1800 castleSide++ //large, then small
1801 ) {
b4ae3ff6
BA
1802 if (this.castleFlags[c][castleSide] >= this.size.y)
1803 continue;
41534b92
BA
1804 // If this code is reached, rook and king are on initial position
1805
1806 // NOTE: in some variants this is not a rook
1807 const rookPos = this.castleFlags[c][castleSide];
cc2c7183 1808 const castlingPiece = this.getPiece(x, rookPos);
41534b92
BA
1809 if (
1810 this.board[x][rookPos] == "" ||
1811 this.getColor(x, rookPos) != c ||
1812 (!!castleWith && !castleWith.includes(castlingPiece))
1813 ) {
1814 // Rook is not here, or changed color (see Benedict)
1815 continue;
1816 }
1817 // Nothing on the path of the king ? (and no checks)
1818 const finDist = finalSquares[castleSide][0] - y;
1819 let step = finDist / Math.max(1, Math.abs(finDist));
1820 let i = y;
1821 do {
1822 if (
1823 (!castleInCheck && this.underCheck([x, i], oppCol)) ||
1824 (
1825 this.board[x][i] != "" &&
1826 // NOTE: next check is enough, because of chessboard constraints
1827 (this.getColor(x, i) != c || ![rookPos, y].includes(i))
1828 )
1829 ) {
1830 continue castlingCheck;
1831 }
1832 i += step;
1833 } while (i != finalSquares[castleSide][0]);
1834 // Nothing on the path to the rook?
1835 step = (castleSide == 0 ? -1 : 1);
1836 for (i = y + step; i != rookPos; i += step) {
b4ae3ff6
BA
1837 if (this.board[x][i] != "")
1838 continue castlingCheck;
41534b92
BA
1839 }
1840
1841 // Nothing on final squares, except maybe king and castling rook?
1842 for (i = 0; i < 2; i++) {
1843 if (
1844 finalSquares[castleSide][i] != rookPos &&
1845 this.board[x][finalSquares[castleSide][i]] != "" &&
1846 (
1847 finalSquares[castleSide][i] != y ||
1848 this.getColor(x, finalSquares[castleSide][i]) != c
1849 )
1850 ) {
1851 continue castlingCheck;
1852 }
1853 }
1854
1855 // If this code is reached, castle is valid
1856 moves.push(
1857 new Move({
1858 appear: [
1859 new PiPo({
1860 x: x,
1861 y: finalSquares[castleSide][0],
1862 p: castlingKing,
1863 c: c
1864 }),
1865 new PiPo({
1866 x: x,
1867 y: finalSquares[castleSide][1],
1868 p: castlingPiece,
1869 c: c
1870 })
1871 ],
1872 vanish: [
1873 // King might be initially disguised (Titan...)
1874 new PiPo({ x: x, y: y, p: castlingKing, c: c }),
1875 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
1876 ],
1877 end:
1878 Math.abs(y - rookPos) <= 2
c9ab0340
BA
1879 ? {x: x, y: rookPos}
1880 : {x: x, y: y + 2 * (castleSide == 0 ? -1 : 1)}
41534b92
BA
1881 })
1882 );
1883 }
1884
1885 return moves;
1886 }
1887
1888 ////////////////////
1889 // MOVES VALIDATION
1890
082e639a
BA
1891 // Is (king at) given position under check by "oppCol" ?
1892 underCheck([x, y], oppCol) {
b4ae3ff6
BA
1893 if (this.options["taking"] || this.options["dark"])
1894 return false;
082e639a
BA
1895 return (
1896 this.findCapturesOn([x, y], {oppCol: oppCol, one: true}).length >= 1
1897 );
41534b92
BA
1898 }
1899
1900 // Stop at first king found (TODO: multi-kings)
1901 searchKingPos(color) {
1902 for (let i=0; i < this.size.x; i++) {
1903 for (let j=0; j < this.size.y; j++) {
cc2c7183
BA
1904 if (this.getColor(i, j) == color && this.isKing(this.getPiece(i, j)))
1905 return [i, j];
41534b92
BA
1906 }
1907 }
1908 return [-1, -1]; //king not found
1909 }
1910
f5435757
BA
1911 // Some variants (e.g. Refusal) may need to check opponent moves too
1912 filterValid(moves, color) {
b4ae3ff6
BA
1913 if (moves.length == 0)
1914 return [];
f5435757
BA
1915 if (!color)
1916 color = this.turn;
cc2c7183 1917 const oppCol = C.GetOppCol(color);
41534b92
BA
1918 if (this.options["balance"] && [1, 3].includes(this.movesCount)) {
1919 // Forbid moves either giving check or exploding opponent's king:
1920 const oppKingPos = this.searchKingPos(oppCol);
1921 moves = moves.filter(m => {
1922 if (
cc2c7183
BA
1923 m.vanish.some(v => v.c == oppCol && v.p == "k") &&
1924 m.appear.every(a => a.c != oppCol || a.p != "k")
41534b92
BA
1925 )
1926 return false;
1927 this.playOnBoard(m);
1928 const res = !this.underCheck(oppKingPos, color);
1929 this.undoOnBoard(m);
1930 return res;
1931 });
1932 }
b4ae3ff6
BA
1933 if (this.options["taking"] || this.options["dark"])
1934 return moves;
41534b92
BA
1935 const kingPos = this.searchKingPos(color);
1936 let filtered = {}; //avoid re-checking similar moves (promotions...)
1937 return moves.filter(m => {
1938 const key = m.start.x + m.start.y + '.' + m.end.x + m.end.y;
1939 if (!filtered[key]) {
1940 this.playOnBoard(m);
1941 let square = kingPos,
1942 res = true; //a priori valid
cc2c7183 1943 if (m.vanish.some(v => {
6997e386 1944 return C.CannibalKings[v.p] && v.c == color;
cc2c7183 1945 })) {
41534b92
BA
1946 // Search king in appear array:
1947 const newKingIdx =
cc2c7183 1948 m.appear.findIndex(a => {
6997e386 1949 return C.CannibalKings[a.p] && a.c == color;
cc2c7183 1950 });
41534b92
BA
1951 if (newKingIdx >= 0)
1952 square = [m.appear[newKingIdx].x, m.appear[newKingIdx].y];
b4ae3ff6
BA
1953 else
1954 res = false;
41534b92
BA
1955 }
1956 res &&= !this.underCheck(square, oppCol);
1957 this.undoOnBoard(m);
1958 filtered[key] = res;
1959 return res;
1960 }
1961 return filtered[key];
1962 });
1963 }
1964
1965 /////////////////
1966 // MOVES PLAYING
1967
1968 // Aggregate flags into one object
1969 aggregateFlags() {
1970 return this.castleFlags;
1971 }
1972
1973 // Reverse operation
1974 disaggregateFlags(flags) {
1975 this.castleFlags = flags;
1976 }
1977
1978 // Apply a move on board
1979 playOnBoard(move) {
6997e386
BA
1980 for (let psq of move.vanish)
1981 this.board[psq.x][psq.y] = "";
1982 for (let psq of move.appear)
1983 this.board[psq.x][psq.y] = psq.c + psq.p;
41534b92
BA
1984 }
1985 // Un-apply the played move
1986 undoOnBoard(move) {
6997e386
BA
1987 for (let psq of move.appear)
1988 this.board[psq.x][psq.y] = "";
1989 for (let psq of move.vanish)
1990 this.board[psq.x][psq.y] = psq.c + psq.p;
41534b92
BA
1991 }
1992
1993 updateCastleFlags(move) {
1994 // Update castling flags if start or arrive from/at rook/king locations
1995 move.appear.concat(move.vanish).forEach(psq => {
1996 if (
1997 this.board[psq.x][psq.y] != "" &&
cc2c7183 1998 this.getPieceType(psq.x, psq.y) == "k"
41534b92
BA
1999 ) {
2000 this.castleFlags[psq.c] = [this.size.y, this.size.y];
2001 }
2002 // NOTE: not "else if" because king can capture enemy rook...
cc2c7183 2003 let c = "";
b4ae3ff6
BA
2004 if (psq.x == 0)
2005 c = "b";
2006 else if (psq.x == this.size.x - 1)
2007 c = "w";
cc2c7183 2008 if (c != "") {
41534b92 2009 const fidx = this.castleFlags[c].findIndex(f => f == psq.y);
b4ae3ff6
BA
2010 if (fidx >= 0)
2011 this.castleFlags[c][fidx] = this.size.y;
41534b92
BA
2012 }
2013 });
2014 }
2015
2016 prePlay(move) {
2017 if (
99ea2453
BA
2018 this.hasCastle &&
2019 // If flags already off, no need to re-check:
2020 Object.keys(this.castleFlags).some(c => {
2021 return this.castleFlags[c].some(val => val < this.size.y)})
41534b92 2022 ) {
99ea2453
BA
2023 this.updateCastleFlags(move);
2024 }
2025 if (this.options["crazyhouse"]) {
2026 move.vanish.forEach(v => {
2027 const square = C.CoordsToSquare({x: v.x, y: v.y});
2028 if (this.ispawn[square])
2029 delete this.ispawn[square];
2030 });
2031 if (move.appear.length > 0 && move.vanish.length > 0) {
2032 // Assumption: something is moving
2033 const initSquare = C.CoordsToSquare(move.start);
f429756d 2034 const destSquare = C.CoordsToSquare(move.end);
99ea2453
BA
2035 if (
2036 this.ispawn[initSquare] ||
2037 (move.vanish[0].p == "p" && move.appear[0].p != "p")
41534b92 2038 ) {
f429756d
BA
2039 this.ispawn[destSquare] = true;
2040 }
2041 else if (
2042 this.ispawn[destSquare] &&
2043 this.getColor(move.end.x, move.end.y) != move.vanish[0].c
2044 ) {
2045 move.vanish[1].p = "p";
2046 delete this.ispawn[destSquare];
41534b92
BA
2047 }
2048 }
2049 }
2050 const minSize = Math.min(move.appear.length, move.vanish.length);
0c44c676
BA
2051 if (
2052 this.hasReserve &&
2053 // Warning; atomic pawn removal isn't a capture
2054 (!this.options["atomic"] || !this.rempawn || this.movesCount >= 1)
2055 ) {
41534b92
BA
2056 const color = this.turn;
2057 for (let i=minSize; i<move.appear.length; i++) {
2058 // Something appears = dropped on board (some exceptions, Chakart...)
0c44c676
BA
2059 if (move.appear[i].c == color) {
2060 const piece = move.appear[i].p;
2061 this.updateReserve(color, piece, this.reserve[color][piece] - 1);
2062 }
41534b92
BA
2063 }
2064 for (let i=minSize; i<move.vanish.length; i++) {
2065 // Something vanish: add to reserve except if recycle & opponent
0c44c676
BA
2066 if (
2067 this.options["crazyhouse"] ||
2068 (this.options["recycle"] && move.vanish[i].c == color)
2069 ) {
2070 const piece = move.vanish[i].p;
41534b92 2071 this.updateReserve(color, piece, this.reserve[color][piece] + 1);
0c44c676 2072 }
41534b92
BA
2073 }
2074 }
2075 }
2076
2077 play(move) {
2078 this.prePlay(move);
b4ae3ff6
BA
2079 if (this.hasEnpassant)
2080 this.epSquare = this.getEpSquare(move);
41534b92
BA
2081 this.playOnBoard(move);
2082 this.postPlay(move);
2083 }
2084
2085 postPlay(move) {
2086 const color = this.turn;
cc2c7183 2087 const oppCol = C.GetOppCol(color);
b4ae3ff6 2088 if (this.options["dark"])
c9ab0340 2089 this.updateEnlightened();
41534b92
BA
2090 if (this.options["teleport"]) {
2091 if (
cc2c7183 2092 this.subTurnTeleport == 1 &&
41534b92
BA
2093 move.vanish.length > move.appear.length &&
2094 move.vanish[move.vanish.length - 1].c == color
2095 ) {
2096 const v = move.vanish[move.vanish.length - 1];
2097 this.captured = {x: v.x, y: v.y, c: v.c, p: v.p};
cc2c7183 2098 this.subTurnTeleport = 2;
41534b92
BA
2099 return;
2100 }
cc2c7183 2101 this.subTurnTeleport = 1;
41534b92
BA
2102 this.captured = null;
2103 }
2104 if (this.options["balance"]) {
b4ae3ff6
BA
2105 if (![1, 3].includes(this.movesCount))
2106 this.turn = oppCol;
41534b92
BA
2107 }
2108 else {
2109 if (
2110 (
2111 this.options["doublemove"] &&
2112 this.movesCount >= 1 &&
2113 this.subTurn == 1
2114 ) ||
2115 (this.options["progressive"] && this.subTurn <= this.movesCount)
2116 ) {
2117 const oppKingPos = this.searchKingPos(oppCol);
6f74b81a
BA
2118 if (
2119 oppKingPos[0] >= 0 &&
2120 (
2121 this.options["taking"] ||
2122 !this.underCheck(oppKingPos, color)
2123 )
2124 ) {
41534b92
BA
2125 this.subTurn++;
2126 return;
2127 }
2128 }
2129 this.turn = oppCol;
2130 }
2131 this.movesCount++;
2132 this.subTurn = 1;
2133 }
2134
2135 // "Stop at the first move found"
2136 atLeastOneMove(color) {
2137 color = color || this.turn;
2138 for (let i = 0; i < this.size.x; i++) {
2139 for (let j = 0; j < this.size.y; j++) {
2140 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
cc2c7183
BA
2141 // NOTE: in fact searching for all potential moves from i,j.
2142 // I don't believe this is an issue, for now at least.
41534b92 2143 const moves = this.getPotentialMovesFrom([i, j]);
b4ae3ff6
BA
2144 if (moves.some(m => this.filterValid([m]).length >= 1))
2145 return true;
41534b92
BA
2146 }
2147 }
2148 }
2149 if (this.hasReserve && this.reserve[color]) {
2150 for (let p of Object.keys(this.reserve[color])) {
2151 const moves = this.getDropMovesFrom([color, p]);
b4ae3ff6
BA
2152 if (moves.some(m => this.filterValid([m]).length >= 1))
2153 return true;
41534b92
BA
2154 }
2155 }
2156 return false;
2157 }
2158
2159 // What is the score ? (Interesting if game is over)
2160 getCurrentScore(move) {
2161 const color = this.turn;
cc2c7183 2162 const oppCol = C.GetOppCol(color);
41534b92 2163 const kingPos = [this.searchKingPos(color), this.searchKingPos(oppCol)];
b4ae3ff6
BA
2164 if (kingPos[0][0] < 0 && kingPos[1][0] < 0)
2165 return "1/2";
2166 if (kingPos[0][0] < 0)
2167 return (color == "w" ? "0-1" : "1-0");
2168 if (kingPos[1][0] < 0)
2169 return (color == "w" ? "1-0" : "0-1");
2170 if (this.atLeastOneMove())
2171 return "*";
41534b92 2172 // No valid move: stalemate or checkmate?
c9ab0340 2173 if (!this.underCheck(kingPos[0], color))
b4ae3ff6 2174 return "1/2";
41534b92
BA
2175 // OK, checkmate
2176 return (color == "w" ? "0-1" : "1-0");
2177 }
2178
41534b92
BA
2179 playVisual(move, r) {
2180 move.vanish.forEach(v => {
f77da909 2181 this.g_pieces[v.x][v.y].remove();
c9ab0340 2182 this.g_pieces[v.x][v.y] = null;
41534b92 2183 });
3c61449b
BA
2184 let chessboard =
2185 document.getElementById(this.containerId).querySelector(".chessboard");
b4ae3ff6
BA
2186 if (!r)
2187 r = chessboard.getBoundingClientRect();
41534b92
BA
2188 const pieceWidth = this.getPieceWidth(r.width);
2189 move.appear.forEach(a => {
41534b92 2190 this.g_pieces[a.x][a.y] = document.createElement("piece");
3b641716 2191 C.AddClass_es(this.g_pieces[a.x][a.y], this.pieces()[a.p]["class"]);
bc2bc396 2192 this.g_pieces[a.x][a.y].classList.add(C.GetColorClass(a.c));
41534b92
BA
2193 this.g_pieces[a.x][a.y].style.width = pieceWidth + "px";
2194 this.g_pieces[a.x][a.y].style.height = pieceWidth + "px";
2195 const [ip, jp] = this.getPixelPosition(a.x, a.y, r);
9db5050a
BA
2196 // Translate coordinates to use chessboard as reference:
2197 this.g_pieces[a.x][a.y].style.transform =
2198 `translate(${ip - r.x}px,${jp - r.y}px)`;
c9ab0340
BA
2199 if (this.enlightened && !this.enlightened[a.x][a.y])
2200 this.g_pieces[a.x][a.y].classList.add("hidden");
3c61449b 2201 chessboard.appendChild(this.g_pieces[a.x][a.y]);
41534b92 2202 });
c9ab0340
BA
2203 if (this.options["dark"])
2204 this.graphUpdateEnlightened();
41534b92
BA
2205 }
2206
2207 playPlusVisual(move, r) {
41534b92 2208 this.play(move);
c9ab0340 2209 this.playVisual(move, r);
41534b92
BA
2210 this.afterPlay(move); //user method
2211 }
2212
15106e82
BA
2213 getMaxDistance(rwidth) {
2214 // Works for all rectangular boards:
2215 return Math.sqrt(rwidth ** 2 + (rwidth / this.size.ratio) ** 2);
2216 }
2217
2218 getDomPiece(x, y) {
2219 return (typeof x == "string" ? this.r_pieces : this.g_pieces)[x][y];
41534b92
BA
2220 }
2221
2222 animate(move, callback) {
15106e82 2223 if (this.noAnimate || move.noAnimate) {
e8b85c86
BA
2224 callback();
2225 return;
2226 }
9db5050a 2227 let initPiece = this.getDomPiece(move.start.x, move.start.y);
9db5050a
BA
2228 // NOTE: cloning generally not required, but light enough, and simpler
2229 let movingPiece = initPiece.cloneNode();
2230 initPiece.style.opacity = "0";
2231 let container =
2232 document.getElementById(this.containerId)
2233 const r = container.querySelector(".chessboard").getBoundingClientRect();
082e639a
BA
2234 if (typeof move.start.x == "string") {
2235 // Need to bound width/height (was 100% for reserve pieces)
2236 const pieceWidth = this.getPieceWidth(r.width);
2237 movingPiece.style.width = pieceWidth + "px";
2238 movingPiece.style.height = pieceWidth + "px";
2239 }
15106e82 2240 const maxDist = this.getMaxDistance(r.width);
9db5050a 2241 const pieces = this.pieces();
15106e82 2242 if (move.drag) {
15106e82 2243 const startCode = this.getPiece(move.start.x, move.start.y);
3b641716
BA
2244 C.RemoveClass_es(movingPiece, pieces[startCode]["class"]);
2245 C.AddClass_es(movingPiece, pieces[move.drag.p]["class"]);
15106e82
BA
2246 const apparentColor = this.getColor(move.start.x, move.start.y);
2247 if (apparentColor != move.drag.c) {
2248 movingPiece.classList.remove(C.GetColorClass(apparentColor));
2249 movingPiece.classList.add(C.GetColorClass(move.drag.c));
41534b92 2250 }
41534b92 2251 }
9db5050a 2252 container.appendChild(movingPiece);
15106e82 2253 const animateSegment = (index, cb) => {
9db5050a 2254 // NOTE: move.drag could be generalized per-segment (usage?)
15106e82
BA
2255 const [i1, j1] = move.segments[index][0];
2256 const [i2, j2] = move.segments[index][1];
2257 const dep = this.getPixelPosition(i1, j1, r);
2258 const arr = this.getPixelPosition(i2, j2, r);
9db5050a
BA
2259 movingPiece.style.transitionDuration = "0s";
2260 movingPiece.style.transform = `translate(${dep[0]}px, ${dep[1]}px)`;
15106e82
BA
2261 const distance =
2262 Math.sqrt((arr[0] - dep[0]) ** 2 + (arr[1] - dep[1]) ** 2);
2263 const duration = 0.2 + (distance / maxDist) * 0.3;
9db5050a
BA
2264 // TODO: unclear why we need this new delay below:
2265 setTimeout(() => {
2266 movingPiece.style.transitionDuration = duration + "s";
adf7c659 2267 // movingPiece is child of container: no need to adjust coordinates
9db5050a
BA
2268 movingPiece.style.transform = `translate(${arr[0]}px, ${arr[1]}px)`;
2269 setTimeout(cb, duration * 1000);
2270 }, 50);
15106e82 2271 };
635418a5
BA
2272 if (!move.segments) {
2273 move.segments = [
2274 [[move.start.x, move.start.y], [move.end.x, move.end.y]]
2275 ];
2276 }
15106e82 2277 let index = 0;
635418a5 2278 const animateSegmentCallback = () => {
15106e82 2279 if (index < move.segments.length)
635418a5 2280 animateSegment(index++, animateSegmentCallback);
15106e82 2281 else {
9db5050a
BA
2282 movingPiece.remove();
2283 initPiece.style.opacity = "1";
41534b92 2284 callback();
15106e82 2285 }
635418a5
BA
2286 };
2287 animateSegmentCallback();
41534b92
BA
2288 }
2289
2290 playReceivedMove(moves, callback) {
21e8e712 2291 const launchAnimation = () => {
3c61449b 2292 const r = container.querySelector(".chessboard").getBoundingClientRect();
21e8e712
BA
2293 const animateRec = i => {
2294 this.animate(moves[i], () => {
21e8e712 2295 this.play(moves[i]);
57b8015b 2296 this.playVisual(moves[i], r);
b4ae3ff6
BA
2297 if (i < moves.length - 1)
2298 setTimeout(() => animateRec(i+1), 300);
2299 else
2300 callback();
21e8e712
BA
2301 });
2302 };
2303 animateRec(0);
2304 };
e081c5eb
BA
2305 // Delay if user wasn't focused:
2306 const checkDisplayThenAnimate = (delay) => {
3c61449b 2307 if (container.style.display == "none") {
21e8e712
BA
2308 alert("New move! Let's go back to game...");
2309 document.getElementById("gameInfos").style.display = "none";
3c61449b 2310 container.style.display = "block";
21e8e712
BA
2311 setTimeout(launchAnimation, 700);
2312 }
b4ae3ff6
BA
2313 else
2314 setTimeout(launchAnimation, delay || 0);
21e8e712 2315 };
3c61449b 2316 let container = document.getElementById(this.containerId);
016306e3
BA
2317 if (document.hidden) {
2318 document.onvisibilitychange = () => {
2319 document.onvisibilitychange = undefined;
e081c5eb 2320 checkDisplayThenAnimate(700);
fd31883b 2321 };
fd31883b 2322 }
b4ae3ff6
BA
2323 else
2324 checkDisplayThenAnimate();
41534b92
BA
2325 }
2326
2327};