Add Avalanche, write Avalam rules
[xogo.git] / base_rules.js
CommitLineData
9b760538
BA
1import {Random} from "/utils/alea.js";
2import {ArrayFun} from "/utils/array.js";
41534b92
BA
3import PiPo from "/utils/PiPo.js";
4import Move from "/utils/Move.js";
5
5f08c59b
BA
6// Helper class for move animation
7class TargetObj {
8
9 constructor(callOnComplete) {
10 this.value = 0;
11 this.target = 0;
12 this.callOnComplete = callOnComplete;
13 }
14 increment() {
15 if (++this.value == this.target)
16 this.callOnComplete();
17 }
18
19};
20
41534b92 21// NOTE: x coords: top to bottom (white perspective); y: left to right
cc2c7183 22// NOTE: ChessRules is aliased as window.C, and variants as window.V
41534b92
BA
23export default class ChessRules {
24
e5f93427 25 static get Aliases() {
3caec36f 26 return {'C': ChessRules};
e5f93427
BA
27 }
28
41534b92
BA
29 /////////////////////////
30 // VARIANT SPECIFICATIONS
31
32 // Some variants have specific options, like the number of pawns in Monster,
33 // or the board size for Pandemonium.
34 // Users can generally select a randomness level from 0 to 2.
35 static get Options() {
36 return {
41534b92
BA
37 select: [{
38 label: "Randomness",
39 variable: "randomness",
40 defaut: 0,
41 options: [
b4ae3ff6
BA
42 {label: "Deterministic", value: 0},
43 {label: "Symmetric random", value: 1},
44 {label: "Asymmetric random", value: 2}
41534b92
BA
45 ]
46 }],
437dfd42 47 input: [
f8b43ef7
BA
48 {
49 label: "Capture king",
437dfd42
BA
50 variable: "taking",
51 type: "checkbox",
52 defaut: false
f8b43ef7
BA
53 },
54 {
55 label: "Falling pawn",
437dfd42
BA
56 variable: "pawnfall",
57 type: "checkbox",
58 defaut: false
f8b43ef7
BA
59 }
60 ],
41534b92
BA
61 // Game modifiers (using "elementary variants"). Default: false
62 styles: [
63 "atomic",
64 "balance", //takes precedence over doublemove & progressive
65 "cannibal",
66 "capture",
67 "crazyhouse",
68 "cylinder", //ok with all
69 "dark",
70 "doublemove",
71 "madrasi",
72 "progressive", //(natural) priority over doublemove
73 "recycle",
74 "rifle",
75 "teleport",
76 "zen"
77 ]
78 };
79 }
80
c9ab0340
BA
81 get pawnPromotions() {
82 return ['q', 'r', 'n', 'b'];
41534b92
BA
83 }
84
85 // Some variants don't have flags:
86 get hasFlags() {
87 return true;
88 }
89 // Or castle
90 get hasCastle() {
91 return this.hasFlags;
92 }
93
94 // En-passant captures allowed?
95 get hasEnpassant() {
96 return true;
97 }
98
99 get hasReserve() {
100 return (
101 !!this.options["crazyhouse"] ||
102 (!!this.options["recycle"] && !this.options["teleport"])
103 );
104 }
24872b22
BA
105 // Some variants do not store reserve state (Align4, Chakart...)
106 get hasReserveFen() {
107 return this.hasReserve;
108 }
41534b92
BA
109
110 get noAnimate() {
111 return !!this.options["dark"];
112 }
113
6b9320bb
BA
114 // Some variants use only click information
115 get clickOnly() {
116 return false;
117 }
118
98d14451 119 // Some variants reveal moves only after both players played
126ffc70 120 get hideMoves() {
98d14451
BA
121 return false;
122 }
123
41534b92 124 // Some variants use click infos:
15106e82
BA
125 doClick(coords) {
126 if (typeof coords.x != "number")
b4ae3ff6 127 return null; //click on reserves
41534b92 128 if (
cc2c7183 129 this.options["teleport"] && this.subTurnTeleport == 2 &&
15106e82 130 this.board[coords.x][coords.y] == ""
41534b92 131 ) {
1a7c0492 132 let res = new Move({
41534b92
BA
133 start: {x: this.captured.x, y: this.captured.y},
134 appear: [
135 new PiPo({
15106e82
BA
136 x: coords.x,
137 y: coords.y,
ca8a3993 138 c: this.captured.c,
41534b92
BA
139 p: this.captured.p
140 })
141 ],
1a7c0492 142 vanish: []
41534b92 143 });
1a7c0492
BA
144 res.drag = {c: this.captured.c, p: this.captured.p};
145 return res;
41534b92
BA
146 }
147 return null;
148 }
149
150 ////////////////////
151 // COORDINATES UTILS
152
4bff03f5 153 // 3a --> {x:3, y:10}
41534b92 154 static SquareToCoords(sq) {
15106e82
BA
155 return ArrayFun.toObject(["x", "y"],
156 [0, 1].map(i => parseInt(sq[i], 36)));
41534b92
BA
157 }
158
4bff03f5 159 // {x:11, y:12} --> bc
15106e82
BA
160 static CoordsToSquare(cd) {
161 return Object.values(cd).map(c => c.toString(36)).join("");
41534b92
BA
162 }
163
15106e82
BA
164 coordsToId(cd) {
165 if (typeof cd.x == "number") {
166 return (
167 `${this.containerId}|sq-${cd.x.toString(36)}-${cd.y.toString(36)}`
168 );
169 }
41534b92 170 // Reserve :
15106e82 171 return `${this.containerId}|rsq-${cd.x}-${cd.y}`;
41534b92
BA
172 }
173
174 idToCoords(targetId) {
b4ae3ff6
BA
175 if (!targetId)
176 return null; //outside page, maybe...
41534b92
BA
177 const idParts = targetId.split('|'); //prefix|sq-2-3 (start at 0 => 3,4)
178 if (
179 idParts.length < 2 ||
180 idParts[0] != this.containerId ||
181 !idParts[1].match(/sq-[0-9a-zA-Z]-[0-9a-zA-Z]/)
182 ) {
183 return null;
184 }
185 const squares = idParts[1].split('-');
186 if (squares[0] == "sq")
15106e82
BA
187 return {x: parseInt(squares[1], 36), y: parseInt(squares[2], 36)};
188 // squares[0] == "rsq" : reserve, 'c' + 'p' (letters color & piece)
189 return {x: squares[1], y: squares[2]};
41534b92
BA
190 }
191
192 /////////////
193 // FEN UTILS
194
195 // Turn "wb" into "B" (for FEN)
196 board2fen(b) {
4bff03f5 197 return (b[0] == "w" ? b[1].toUpperCase() : b[1]);
41534b92
BA
198 }
199
200 // Turn "p" into "bp" (for board)
201 fen2board(f) {
4bff03f5 202 return (f.charCodeAt(0) <= 90 ? "w" + f.toLowerCase() : "b" + f);
41534b92
BA
203 }
204
41534b92 205 genRandInitFen(seed) {
f31de5e4
BA
206 Random.setSeed(seed); //may be unused
207 let baseFen = this.genRandInitBaseFen();
208 baseFen.o = Object.assign({init: true}, baseFen.o);
209 const parts = this.getPartFen(baseFen.o);
210 return (
211 baseFen.fen +
212 (Object.keys(parts).length > 0 ? (" " + JSON.stringify(parts)) : "")
213 );
214 }
215
216 // Setup the initial random-or-not (asymmetric-or-not) position
217 genRandInitBaseFen() {
41534b92 218 let fen, flags = "0707";
cc2c7183 219 if (!this.options.randomness)
41534b92
BA
220 // Deterministic:
221 fen = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w 0";
222
223 else {
224 // Randomize
f382c57b 225 let pieces = {w: new Array(8), b: new Array(8)};
41534b92
BA
226 flags = "";
227 // Shuffle pieces on first (and last rank if randomness == 2)
228 for (let c of ["w", "b"]) {
229 if (c == 'b' && this.options.randomness == 1) {
230 pieces['b'] = pieces['w'];
231 flags += flags;
232 break;
233 }
41534b92 234 let positions = ArrayFun.range(8);
41534b92
BA
235 // Get random squares for bishops
236 let randIndex = 2 * Random.randInt(4);
237 const bishop1Pos = positions[randIndex];
238 // The second bishop must be on a square of different color
239 let randIndex_tmp = 2 * Random.randInt(4) + 1;
240 const bishop2Pos = positions[randIndex_tmp];
241 // Remove chosen squares
242 positions.splice(Math.max(randIndex, randIndex_tmp), 1);
243 positions.splice(Math.min(randIndex, randIndex_tmp), 1);
41534b92
BA
244 // Get random squares for knights
245 randIndex = Random.randInt(6);
246 const knight1Pos = positions[randIndex];
247 positions.splice(randIndex, 1);
248 randIndex = Random.randInt(5);
249 const knight2Pos = positions[randIndex];
250 positions.splice(randIndex, 1);
41534b92
BA
251 // Get random square for queen
252 randIndex = Random.randInt(4);
253 const queenPos = positions[randIndex];
254 positions.splice(randIndex, 1);
41534b92
BA
255 // Rooks and king positions are now fixed,
256 // because of the ordering rook-king-rook
257 const rook1Pos = positions[0];
258 const kingPos = positions[1];
259 const rook2Pos = positions[2];
41534b92
BA
260 // Finally put the shuffled pieces in the board array
261 pieces[c][rook1Pos] = "r";
262 pieces[c][knight1Pos] = "n";
263 pieces[c][bishop1Pos] = "b";
264 pieces[c][queenPos] = "q";
265 pieces[c][kingPos] = "k";
266 pieces[c][bishop2Pos] = "b";
267 pieces[c][knight2Pos] = "n";
268 pieces[c][rook2Pos] = "r";
269 flags += rook1Pos.toString() + rook2Pos.toString();
270 }
271 fen = (
272 pieces["b"].join("") +
273 "/pppppppp/8/8/8/8/PPPPPPPP/" +
274 pieces["w"].join("").toUpperCase() +
275 " w 0"
276 );
277 }
f31de5e4 278 return { fen: fen, o: {flags: flags} };
41534b92
BA
279 }
280
281 // "Parse" FEN: just return untransformed string data
282 parseFen(fen) {
283 const fenParts = fen.split(" ");
284 let res = {
285 position: fenParts[0],
286 turn: fenParts[1],
287 movesCount: fenParts[2]
288 };
b4ae3ff6
BA
289 if (fenParts.length > 3)
290 res = Object.assign(res, JSON.parse(fenParts[3]));
41534b92
BA
291 return res;
292 }
293
294 // Return current fen (game state)
295 getFen() {
f31de5e4
BA
296 const parts = this.getPartFen({});
297 return (
298 this.getBaseFen() +
299 (Object.keys(parts).length > 0 ? (" " + JSON.stringify(parts)) : "")
41534b92 300 );
f31de5e4
BA
301 }
302
303 getBaseFen() {
304 return this.getPosition() + " " + this.turn + " " + this.movesCount;
305 }
306
307 getPartFen(o) {
308 let parts = {};
b4ae3ff6 309 if (this.hasFlags)
f31de5e4 310 parts["flags"] = o.init ? o.flags : this.getFlagsFen();
41534b92 311 if (this.hasEnpassant)
f31de5e4 312 parts["enpassant"] = o.init ? "-" : this.getEnpassantFen();
24872b22 313 if (this.hasReserveFen)
f31de5e4 314 parts["reserve"] = this.getReserveFen(o);
41534b92 315 if (this.options["crazyhouse"])
f31de5e4
BA
316 parts["ispawn"] = this.getIspawnFen(o);
317 return parts;
41534b92
BA
318 }
319
d621e620
BA
320 static FenEmptySquares(count) {
321 // if more than 9 consecutive free spaces, break the integer,
322 // otherwise FEN parsing will fail.
323 if (count <= 9)
324 return count;
325 // Most boards of size < 18:
326 if (count <= 18)
327 return "9" + (count - 9);
328 // Except Gomoku:
329 return "99" + (count - 18);
330 }
331
41534b92 332 // Position part of the FEN string
15106e82 333 getPosition() {
41534b92
BA
334 let position = "";
335 for (let i = 0; i < this.size.y; i++) {
336 let emptyCount = 0;
337 for (let j = 0; j < this.size.x; j++) {
b4ae3ff6
BA
338 if (this.board[i][j] == "")
339 emptyCount++;
41534b92
BA
340 else {
341 if (emptyCount > 0) {
342 // Add empty squares in-between
d621e620 343 position += C.FenEmptySquares(emptyCount);
41534b92
BA
344 emptyCount = 0;
345 }
346 position += this.board2fen(this.board[i][j]);
347 }
348 }
349 if (emptyCount > 0)
350 // "Flush remainder"
d621e620 351 position += C.FenEmptySquares(emptyCount);
b4ae3ff6
BA
352 if (i < this.size.y - 1)
353 position += "/"; //separate rows
41534b92
BA
354 }
355 return position;
356 }
357
41534b92
BA
358 // Flags part of the FEN string
359 getFlagsFen() {
360 return ["w", "b"].map(c => {
15106e82 361 return this.castleFlags[c].map(x => x.toString(36)).join("");
41534b92
BA
362 }).join("");
363 }
364
365 // Enpassant part of the FEN string
366 getEnpassantFen() {
b4ae3ff6 367 if (!this.epSquare)
f31de5e4 368 return "-";
cc2c7183 369 return C.CoordsToSquare(this.epSquare);
41534b92
BA
370 }
371
f31de5e4
BA
372 getReserveFen(o) {
373 if (o.init)
374 return "000000000000";
41534b92
BA
375 return (
376 ["w","b"].map(c => Object.values(this.reserve[c]).join("")).join("")
377 );
378 }
379
f31de5e4
BA
380 getIspawnFen(o) {
381 if (o.init)
382 // NOTE: cannot merge because this.ispawn doesn't exist yet
383 return "-";
15106e82
BA
384 const squares = Object.keys(this.ispawn);
385 if (squares.length == 0)
b4ae3ff6 386 return "-";
15106e82 387 return squares.join(",");
41534b92
BA
388 }
389
390 // Set flags from fen (castle: white a,h then black a,h)
391 setFlags(fenflags) {
392 this.castleFlags = {
15106e82
BA
393 w: [0, 1].map(i => parseInt(fenflags.charAt(i), 36)),
394 b: [2, 3].map(i => parseInt(fenflags.charAt(i), 36))
41534b92
BA
395 };
396 }
397
398 //////////////////
399 // INITIALIZATION
400
bc2bc396 401 constructor(o) {
41534b92 402 this.options = o.options;
535c464b
BA
403 // Fill missing options (always the case if random challenge)
404 (V.Options.select || []).concat(V.Options.input || []).forEach(opt => {
405 if (this.options[opt.variable] === undefined)
406 this.options[opt.variable] = opt.defaut;
407 });
bc2bc396 408 if (o.genFenOnly)
f382c57b
BA
409 // This object will be used only for initial FEN generation
410 return;
f31de5e4
BA
411
412 // Some variables
41534b92 413 this.playerColor = o.color;
15106e82 414 this.afterPlay = o.afterPlay; //trigger some actions after playing a move
f31de5e4
BA
415 this.containerId = o.element;
416 this.isDiagram = o.diagram;
417 this.marks = o.marks;
41534b92 418
f31de5e4 419 // Initializations
b4ae3ff6
BA
420 if (!o.fen)
421 o.fen = this.genRandInitFen(o.seed);
5f08c59b 422 this.re_initFromFen(o.fen);
41534b92
BA
423 this.graphicalInit();
424 }
425
5f08c59b
BA
426 re_initFromFen(fen, oldBoard) {
427 const fenParsed = this.parseFen(fen);
428 this.board = oldBoard || this.getBoard(fenParsed.position);
429 this.turn = fenParsed.turn;
430 this.movesCount = parseInt(fenParsed.movesCount, 10);
431 this.setOtherVariables(fenParsed);
432 }
433
41534b92
BA
434 // Turn position fen into double array ["wb","wp","bk",...]
435 getBoard(position) {
436 const rows = position.split("/");
437 let board = ArrayFun.init(this.size.x, this.size.y, "");
438 for (let i = 0; i < rows.length; i++) {
439 let j = 0;
440 for (let indexInRow = 0; indexInRow < rows[i].length; indexInRow++) {
441 const character = rows[i][indexInRow];
442 const num = parseInt(character, 10);
443 // If num is a number, just shift j:
b4ae3ff6
BA
444 if (!isNaN(num))
445 j += num;
41534b92 446 // Else: something at position i,j
b4ae3ff6
BA
447 else
448 board[i][j++] = this.fen2board(character);
41534b92
BA
449 }
450 }
451 return board;
452 }
453
454 // Some additional variables from FEN (variant dependant)
455 setOtherVariables(fenParsed) {
456 // Set flags and enpassant:
b4ae3ff6
BA
457 if (this.hasFlags)
458 this.setFlags(fenParsed.flags);
41534b92
BA
459 if (this.hasEnpassant)
460 this.epSquare = this.getEpSquare(fenParsed.enpassant);
549ca151 461 if (this.hasReserve && !this.isDiagram)
b4ae3ff6
BA
462 this.initReserves(fenParsed.reserve);
463 if (this.options["crazyhouse"])
464 this.initIspawn(fenParsed.ispawn);
cc2c7183
BA
465 if (this.options["teleport"]) {
466 this.subTurnTeleport = 1;
467 this.captured = null;
468 }
41534b92 469 if (this.options["dark"]) {
41534b92 470 // Setup enlightened: squares reachable by player side
c9ab0340
BA
471 this.enlightened = ArrayFun.init(this.size.x, this.size.y, false);
472 this.updateEnlightened();
41534b92 473 }
5f08c59b
BA
474 this.subTurn = 1; //may be unused
475 if (!this.moveStack) //avoid resetting (unwanted)
476 this.moveStack = [];
41534b92
BA
477 }
478
ca8a3993 479 // ordering as in pieces() p,r,n,b,q,k
41534b92 480 initReserves(reserveStr) {
ca8a3993 481 const counts = reserveStr.split("").map(c => parseInt(c, 36));
41534b92 482 this.reserve = { w: {}, b: {} };
c9ab0340
BA
483 const pieceName = ['p', 'r', 'n', 'b', 'q', 'k'];
484 const L = pieceName.length;
485 for (let i of ArrayFun.range(2 * L)) {
486 if (i < L)
b4ae3ff6
BA
487 this.reserve['w'][pieceName[i]] = counts[i];
488 else
c9ab0340 489 this.reserve['b'][pieceName[i-L]] = counts[i];
41534b92
BA
490 }
491 }
492
493 initIspawn(ispawnStr) {
15106e82
BA
494 if (ispawnStr != "-")
495 this.ispawn = ArrayFun.toObject(ispawnStr.split(","), true);
b4ae3ff6
BA
496 else
497 this.ispawn = {};
41534b92
BA
498 }
499
ca8a3993
BA
500 ////////////////
501 // VISUAL UTILS
502
503 getPieceWidth(rwidth) {
504 return (rwidth / this.size.y);
505 }
506
507 getReserveSquareSize(rwidth, nbR) {
508 const sqSize = this.getPieceWidth(rwidth);
509 return Math.min(sqSize, rwidth / nbR);
510 }
511
512 getReserveNumId(color, piece) {
513 return `${this.containerId}|rnum-${color}${piece}`;
514 }
515
41534b92
BA
516 getNbReservePieces(color) {
517 return (
518 Object.values(this.reserve[color]).reduce(
519 (oldV,newV) => oldV + (newV > 0 ? 1 : 0), 0)
520 );
521 }
522
15106e82
BA
523 getRankInReserve(c, p) {
524 const pieces = Object.keys(this.pieces());
525 const lastIndex = pieces.findIndex(pp => pp == p)
526 let toTest = pieces.slice(0, lastIndex);
527 return toTest.reduce(
528 (oldV,newV) => oldV + (this.reserve[c][newV] > 0 ? 1 : 0), 0);
529 }
530
9b760538 531 static AddClass_es(elt, class_es) {
3b641716
BA
532 if (!Array.isArray(class_es))
533 class_es = [class_es];
9b760538 534 class_es.forEach(cl => elt.classList.add(cl));
3b641716
BA
535 }
536
9b760538 537 static RemoveClass_es(elt, class_es) {
3b641716
BA
538 if (!Array.isArray(class_es))
539 class_es = [class_es];
9b760538 540 class_es.forEach(cl => elt.classList.remove(cl));
3b641716
BA
541 }
542
ca8a3993
BA
543 // Generally light square bottom-right
544 getSquareColorClass(x, y) {
545 return ((x+y) % 2 == 0 ? "light-square": "dark-square");
546 }
547
548 getMaxDistance(r) {
549 // Works for all rectangular boards:
550 return Math.sqrt(r.width ** 2 + r.height ** 2);
551 }
552
553 getDomPiece(x, y) {
554 return (typeof x == "string" ? this.r_pieces : this.g_pieces)[x][y];
555 }
556
557 //////////////////
558 // VISUAL METHODS
559
41534b92 560 graphicalInit() {
65c770d1
BA
561 const g_init = () => {
562 this.re_drawBoardElements();
549ca151 563 if (!this.isDiagram && !this.mouseListeners && !this.touchListeners)
5abaabb3 564 this.initMouseEvents();
65c770d1
BA
565 };
566 let container = document.getElementById(this.containerId);
549ca151
BA
567 this.windowResizeObs = new ResizeObserver(g_init);
568 this.windowResizeObs.observe(container);
41534b92
BA
569 }
570
571 re_drawBoardElements() {
572 const board = this.getSvgChessboard();
cc2c7183 573 const oppCol = C.GetOppCol(this.playerColor);
e7b64798
BA
574 const container = document.getElementById(this.containerId);
575 const rc = container.getBoundingClientRect();
576 let chessboard = container.querySelector(".chessboard");
3c61449b
BA
577 chessboard.innerHTML = "";
578 chessboard.insertAdjacentHTML('beforeend', board);
41534b92 579 // Compare window ratio width / height to aspectRatio:
e7b64798 580 const windowRatio = rc.width / rc.height;
41534b92 581 let cbWidth, cbHeight;
f55a0a67
BA
582 const vRatio = this.size.ratio || 1;
583 if (windowRatio <= vRatio) {
41534b92 584 // Limiting dimension is width:
e7b64798 585 cbWidth = Math.min(rc.width, 767);
f55a0a67 586 cbHeight = cbWidth / vRatio;
41534b92
BA
587 }
588 else {
589 // Limiting dimension is height:
e7b64798 590 cbHeight = Math.min(rc.height, 767);
f55a0a67 591 cbWidth = cbHeight * vRatio;
41534b92 592 }
549ca151 593 if (this.hasReserve && !this.isDiagram) {
41534b92
BA
594 const sqSize = cbWidth / this.size.y;
595 // NOTE: allocate space for reserves (up/down) even if they are empty
15106e82 596 // Cannot use getReserveSquareSize() here, but sqSize is an upper bound.
e7b64798
BA
597 if ((rc.height - cbHeight) / 2 < sqSize + 5) {
598 cbHeight = rc.height - 2 * (sqSize + 5);
f55a0a67 599 cbWidth = cbHeight * vRatio;
41534b92
BA
600 }
601 }
3c61449b
BA
602 chessboard.style.width = cbWidth + "px";
603 chessboard.style.height = cbHeight + "px";
41534b92 604 // Center chessboard:
e7b64798
BA
605 const spaceLeft = (rc.width - cbWidth) / 2,
606 spaceTop = (rc.height - cbHeight) / 2;
3c61449b
BA
607 chessboard.style.left = spaceLeft + "px";
608 chessboard.style.top = spaceTop + "px";
41534b92
BA
609 // Give sizes instead of recomputing them,
610 // because chessboard might not be drawn yet.
611 this.setupPieces({
612 width: cbWidth,
613 height: cbHeight,
614 x: spaceLeft,
615 y: spaceTop
616 });
617 }
618
619 // Get SVG board (background, no pieces)
620 getSvgChessboard() {
41534b92
BA
621 const flipped = (this.playerColor == 'b');
622 let board = `
623 <svg
f55a0a67 624 viewBox="0 0 ${10*this.size.y} ${10*this.size.x}"
535c464b 625 class="chessboard_SVG">`;
728cb1e3
BA
626 for (let i=0; i < this.size.x; i++) {
627 for (let j=0; j < this.size.y; j++) {
9b760538
BA
628 if (!this.onBoard(i, j))
629 continue;
41534b92
BA
630 const ii = (flipped ? this.size.x - 1 - i : i);
631 const jj = (flipped ? this.size.y - 1 - j : j);
c7bf7b1b
BA
632 let classes = this.getSquareColorClass(ii, jj);
633 if (this.enlightened && !this.enlightened[ii][jj])
634 classes += " in-shadow";
41534b92 635 // NOTE: x / y reversed because coordinates system is reversed.
535c464b
BA
636 board += `
637 <rect
638 class="${classes}"
639 id="${this.coordsToId({x: ii, y: jj})}"
640 width="10"
641 height="10"
642 x="${10*j}"
643 y="${10*i}"
644 />`;
41534b92
BA
645 }
646 }
535c464b 647 board += "</svg>";
41534b92
BA
648 return board;
649 }
650
41534b92 651 setupPieces(r) {
3c61449b
BA
652 let chessboard =
653 document.getElementById(this.containerId).querySelector(".chessboard");
b4ae3ff6
BA
654 if (!r)
655 r = chessboard.getBoundingClientRect();
41534b92 656 const pieceWidth = this.getPieceWidth(r.width);
b2fc1259
BA
657 const addPiece = (i, j, arrName, classes) => {
658 this[arrName][i][j] = document.createElement("piece");
659 C.AddClass_es(this[arrName][i][j], classes);
660 this[arrName][i][j].style.width = pieceWidth + "px";
661 this[arrName][i][j].style.height = pieceWidth + "px";
662 let [ip, jp] = this.getPixelPosition(i, j, r);
663 // Translate coordinates to use chessboard as reference:
664 this[arrName][i][j].style.transform =
665 `translate(${ip - r.x}px,${jp - r.y}px)`;
666 chessboard.appendChild(this[arrName][i][j]);
667 };
668 const conditionalReset = (arrName) => {
669 if (this[arrName]) {
670 // Refreshing: delete old pieces first. This isn't necessary,
671 // but simpler (this method isn't called many times)
672 for (let i=0; i<this.size.x; i++) {
673 for (let j=0; j<this.size.y; j++) {
674 if (this[arrName][i][j]) {
675 this[arrName][i][j].remove();
676 this[arrName][i][j] = null;
677 }
678 }
679 }
680 }
681 else
682 this[arrName] = ArrayFun.init(this.size.x, this.size.y, null);
683 if (arrName == "d_pieces")
684 this.marks.forEach(([i, j]) => addPiece(i, j, arrName, "mark"));
685 };
686 if (this.marks)
687 conditionalReset("d_pieces");
688 conditionalReset("g_pieces");
41534b92
BA
689 for (let i=0; i < this.size.x; i++) {
690 for (let j=0; j < this.size.y; j++) {
c9ab0340 691 if (this.board[i][j] != "") {
41534b92 692 const color = this.getColor(i, j);
cc2c7183 693 const piece = this.getPiece(i, j);
b2fc1259 694 addPiece(i, j, "g_pieces", this.pieces(color, i, j)[piece]["class"]);
15106e82 695 this.g_pieces[i][j].classList.add(C.GetColorClass(color));
c9ab0340
BA
696 if (this.enlightened && !this.enlightened[i][j])
697 this.g_pieces[i][j].classList.add("hidden");
b2fc1259
BA
698 }
699 if (this.marks && this.d_pieces[i][j]) {
700 let classes = ["mark"];
701 if (this.board[i][j] != "")
702 classes.push("transparent");
703 addPiece(i, j, "d_pieces", classes);
41534b92
BA
704 }
705 }
706 }
549ca151 707 if (this.hasReserve && !this.isDiagram)
b4ae3ff6 708 this.re_drawReserve(['w', 'b'], r);
41534b92
BA
709 }
710
24872b22 711 // NOTE: assume this.reserve != null
41534b92
BA
712 re_drawReserve(colors, r) {
713 if (this.r_pieces) {
714 // Remove (old) reserve pieces
715 for (let c of colors) {
24872b22
BA
716 Object.keys(this.r_pieces[c]).forEach(p => {
717 this.r_pieces[c][p].remove();
718 delete this.r_pieces[c][p];
719 const numId = this.getReserveNumId(c, p);
720 document.getElementById(numId).remove();
41534b92 721 });
41534b92
BA
722 }
723 }
b4ae3ff6 724 else
9db5050a
BA
725 this.r_pieces = { w: {}, b: {} };
726 let container = document.getElementById(this.containerId);
b4ae3ff6 727 if (!r)
9db5050a 728 r = container.querySelector(".chessboard").getBoundingClientRect();
41534b92 729 for (let c of colors) {
24872b22
BA
730 let reservesDiv = document.getElementById("reserves_" + c);
731 if (reservesDiv)
732 reservesDiv.remove();
b4ae3ff6
BA
733 if (!this.reserve[c])
734 continue;
41534b92 735 const nbR = this.getNbReservePieces(c);
b4ae3ff6
BA
736 if (nbR == 0)
737 continue;
41534b92
BA
738 const sqResSize = this.getReserveSquareSize(r.width, nbR);
739 let ridx = 0;
740 const vShift = (c == this.playerColor ? r.height + 5 : -sqResSize - 5);
741 const [i0, j0] = [r.x, r.y + vShift];
742 let rcontainer = document.createElement("div");
743 rcontainer.id = "reserves_" + c;
744 rcontainer.classList.add("reserves");
745 rcontainer.style.left = i0 + "px";
746 rcontainer.style.top = j0 + "px";
1aa9054d
BA
747 // NOTE: +1 fix display bug on Firefox at least
748 rcontainer.style.width = (nbR * sqResSize + 1) + "px";
41534b92 749 rcontainer.style.height = sqResSize + "px";
9db5050a 750 container.appendChild(rcontainer);
41534b92 751 for (let p of Object.keys(this.reserve[c])) {
b4ae3ff6
BA
752 if (this.reserve[c][p] == 0)
753 continue;
41534b92 754 let r_cell = document.createElement("div");
15106e82 755 r_cell.id = this.coordsToId({x: c, y: p});
41534b92 756 r_cell.classList.add("reserve-cell");
1aa9054d
BA
757 r_cell.style.width = sqResSize + "px";
758 r_cell.style.height = sqResSize + "px";
41534b92
BA
759 rcontainer.appendChild(r_cell);
760 let piece = document.createElement("piece");
2159c239 761 C.AddClass_es(piece, this.pieces(c, c, p)[p]["class"]);
15106e82 762 piece.classList.add(C.GetColorClass(c));
41534b92
BA
763 piece.style.width = "100%";
764 piece.style.height = "100%";
765 this.r_pieces[c][p] = piece;
766 r_cell.appendChild(piece);
767 let number = document.createElement("div");
768 number.textContent = this.reserve[c][p];
769 number.classList.add("reserve-num");
770 number.id = this.getReserveNumId(c, p);
771 const fontSize = "1.3em";
772 number.style.fontSize = fontSize;
773 number.style.fontSize = fontSize;
774 r_cell.appendChild(number);
775 ridx++;
776 }
777 }
778 }
779
780 updateReserve(color, piece, count) {
55a15dcb 781 if (this.options["cannibal"] && C.CannibalKings[piece])
cc2c7183 782 piece = "k"; //capturing cannibal king: back to king form
41534b92
BA
783 const oldCount = this.reserve[color][piece];
784 this.reserve[color][piece] = count;
785 // Redrawing is much easier if count==0
b4ae3ff6
BA
786 if ([oldCount, count].includes(0))
787 this.re_drawReserve([color]);
41534b92
BA
788 else {
789 const numId = this.getReserveNumId(color, piece);
790 document.getElementById(numId).textContent = count;
791 }
792 }
793
c4e9bb92
BA
794 // Resize board: no need to destroy/recreate pieces
795 rescale(mode) {
e7b64798
BA
796 const container = document.getElementById(this.containerId);
797 let chessboard = container.querySelector(".chessboard");
798 const rc = container.getBoundingClientRect(),
799 r = chessboard.getBoundingClientRect();
c4e9bb92
BA
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;
e7b64798
BA
804 if (newWidth > rc.width) {
805 newWidth = rc.width;
f55a0a67 806 newHeight = newWidth / vRatio;
c4e9bb92 807 }
e7b64798
BA
808 if (newHeight > rc.height) {
809 newHeight = rc.height;
f55a0a67 810 newWidth = newHeight * vRatio;
c4e9bb92 811 }
535c464b
BA
812 chessboard.style.width = newWidth + "px";
813 chessboard.style.height = newHeight + "px";
e7b64798 814 const newX = (rc.width - newWidth) / 2;
3c61449b 815 chessboard.style.left = newX + "px";
e7b64798 816 const newY = (rc.height - 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 }
b2fc1259 837 if (this.hasReserve)
c4e9bb92 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 932 if (move)
e7d409fc 933 this.buildMoveStack(move, r);
6b9320bb 934 else if (!this.clickOnly) {
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)
e7d409fc 987 this.buildMoveStack(moves[0], r);
41534b92
BA
988 }
989 curPiece.remove();
990 };
991
a5da6269
BA
992 const resize = (e) => this.rescale(e.deltaY < 0 ? "up" : "down");
993
41534b92 994 if ('onmousedown' in window) {
a5da6269
BA
995 this.mouseListeners = [
996 {type: "mousedown", listener: mousedown},
997 {type: "mousemove", listener: mousemove},
998 {type: "mouseup", listener: mouseup},
999 {type: "wheel", listener: resize}
1000 ];
1001 this.mouseListeners.forEach(ml => {
1002 document.addEventListener(ml.type, ml.listener);
1003 });
41534b92
BA
1004 }
1005 if ('ontouchstart' in window) {
a5da6269
BA
1006 this.touchListeners = [
1007 {type: "touchstart", listener: mousedown},
1008 {type: "touchmove", listener: mousemove},
1009 {type: "touchend", listener: mouseup}
1010 ];
1011 this.touchListeners.forEach(tl => {
1012 // https://stackoverflow.com/a/42509310/12660887
1013 document.addEventListener(tl.type, tl.listener, {passive: false});
1014 });
41534b92 1015 }
11625344 1016 // TODO: onpointerdown/move/up ? See reveal.js /controllers/touch.js
41534b92
BA
1017 }
1018
a5da6269 1019 removeListeners() {
549ca151
BA
1020 let container = document.getElementById(this.containerId);
1021 this.windowResizeObs.unobserve(container);
5abaabb3
BA
1022 if (this.isDiagram)
1023 return; //no listeners in this case
a5da6269
BA
1024 if ('onmousedown' in window) {
1025 this.mouseListeners.forEach(ml => {
1026 document.removeEventListener(ml.type, ml.listener);
1027 });
1028 }
1029 if ('ontouchstart' in window) {
1030 this.touchListeners.forEach(tl => {
1031 // https://stackoverflow.com/a/42509310/12660887
1032 document.removeEventListener(tl.type, tl.listener);
1033 });
1034 }
1035 }
1036
41534b92
BA
1037 showChoices(moves, r) {
1038 let container = document.getElementById(this.containerId);
3c61449b 1039 let chessboard = container.querySelector(".chessboard");
41534b92
BA
1040 let choices = document.createElement("div");
1041 choices.id = "choices";
a2bb7e06
BA
1042 if (!r)
1043 r = chessboard.getBoundingClientRect();
41534b92
BA
1044 choices.style.width = r.width + "px";
1045 choices.style.height = r.height + "px";
1046 choices.style.left = r.x + "px";
1047 choices.style.top = r.y + "px";
3c61449b
BA
1048 chessboard.style.opacity = "0.5";
1049 container.appendChild(choices);
15106e82 1050 const squareWidth = r.width / this.size.y;
41534b92
BA
1051 const firstUpLeft = (r.width - (moves.length * squareWidth)) / 2;
1052 const firstUpTop = (r.height - squareWidth) / 2;
1053 const color = moves[0].appear[0].c;
1054 const callback = (m) => {
3c61449b
BA
1055 chessboard.style.opacity = "1";
1056 container.removeChild(choices);
e7d409fc 1057 this.buildMoveStack(m, r);
41534b92
BA
1058 }
1059 for (let i=0; i < moves.length; i++) {
1060 let choice = document.createElement("div");
1061 choice.classList.add("choice");
1062 choice.style.width = squareWidth + "px";
1063 choice.style.height = squareWidth + "px";
1064 choice.style.left = (firstUpLeft + i * squareWidth) + "px";
1065 choice.style.top = firstUpTop + "px";
1066 choice.style.backgroundColor = "lightyellow";
1067 choice.onclick = () => callback(moves[i]);
1068 const piece = document.createElement("piece");
3b641716 1069 const cdisp = moves[i].choice || moves[i].appear[0].p;
2159c239
BA
1070 C.AddClass_es(piece,
1071 this.pieces(color, moves[i].end.x, moves[i].end.y)[cdisp]["class"]);
15106e82 1072 piece.classList.add(C.GetColorClass(color));
41534b92
BA
1073 piece.style.width = "100%";
1074 piece.style.height = "100%";
1075 choice.appendChild(piece);
1076 choices.appendChild(choice);
1077 }
1078 }
1079
98d14451
BA
1080 displayMessage(elt, msg, classe_s, timeout) {
1081 if (elt)
1082 // Fixed element, e.g. for Dice Chess
1083 elt.innerHTML = msg;
1084 else {
1085 // Temporary div (Chakart, Apocalypse...)
1086 let divMsg = document.createElement("div");
1087 C.AddClass_es(divMsg, classe_s);
1088 divMsg.innerHTML = msg;
1089 let container = document.getElementById(this.containerId);
1090 container.appendChild(divMsg);
1091 setTimeout(() => container.removeChild(divMsg), timeout);
1092 }
1093 }
1094
ca8a3993
BA
1095 ////////////////
1096 // DARK METHODS
1097
1098 updateEnlightened() {
1099 this.oldEnlightened = this.enlightened;
1100 this.enlightened = ArrayFun.init(this.size.x, this.size.y, false);
1101 // Add pieces positions + all squares reachable by moves (includes Zen):
1102 for (let x=0; x<this.size.x; x++) {
1103 for (let y=0; y<this.size.y; y++) {
1104 if (this.board[x][y] != "" && this.getColor(x, y) == this.playerColor)
1105 {
1106 this.enlightened[x][y] = true;
1107 this.getPotentialMovesFrom([x, y]).forEach(m => {
1108 this.enlightened[m.end.x][m.end.y] = true;
1109 });
1110 }
1111 }
1112 }
1113 if (this.epSquare)
1114 this.enlightEnpassant();
1115 }
1116
1117 // Include square of the en-passant capturing square:
1118 enlightEnpassant() {
1119 // NOTE: shortcut, pawn has only one attack type, doesn't depend on square
1120 const steps = this.pieces(this.playerColor)["p"].attack[0].steps;
1121 for (let step of steps) {
1122 const x = this.epSquare.x - step[0],
1123 y = this.getY(this.epSquare.y - step[1]);
1124 if (
1125 this.onBoard(x, y) &&
1126 this.getColor(x, y) == this.playerColor &&
1127 this.getPieceType(x, y) == "p"
1128 ) {
1129 this.enlightened[x][this.epSquare.y] = true;
1130 break;
1131 }
1132 }
1133 }
1134
1135 // Apply diff this.enlightened --> oldEnlightened on board
1136 graphUpdateEnlightened() {
1137 let chessboard =
1138 document.getElementById(this.containerId).querySelector(".chessboard");
1139 const r = chessboard.getBoundingClientRect();
1140 const pieceWidth = this.getPieceWidth(r.width);
1141 for (let x=0; x<this.size.x; x++) {
1142 for (let y=0; y<this.size.y; y++) {
1143 if (!this.enlightened[x][y] && this.oldEnlightened[x][y]) {
1144 let elt = document.getElementById(this.coordsToId({x: x, y: y}));
1145 elt.classList.add("in-shadow");
1146 if (this.g_pieces[x][y])
1147 this.g_pieces[x][y].classList.add("hidden");
1148 }
1149 else if (this.enlightened[x][y] && !this.oldEnlightened[x][y]) {
1150 let elt = document.getElementById(this.coordsToId({x: x, y: y}));
1151 elt.classList.remove("in-shadow");
1152 if (this.g_pieces[x][y])
1153 this.g_pieces[x][y].classList.remove("hidden");
1154 }
1155 }
1156 }
1157 }
1158
41534b92
BA
1159 //////////////
1160 // BASIC UTILS
1161
1162 get size() {
15106e82
BA
1163 return {
1164 x: 8,
1165 y: 8,
f55a0a67 1166 ratio: 1 //for rectangular board = y / x (optional, 1 = default)
15106e82 1167 };
41534b92
BA
1168 }
1169
ca8a3993 1170 // Color of thing on square (i,j). '' if square is empty
41534b92 1171 getColor(i, j) {
15106e82
BA
1172 if (typeof i == "string")
1173 return i; //reserves
41534b92
BA
1174 return this.board[i][j].charAt(0);
1175 }
1176
15106e82 1177 static GetColorClass(c) {
bc2bc396
BA
1178 if (c == 'w')
1179 return "white";
1180 if (c == 'b')
1181 return "black";
24872b22 1182 return "other-color"; //unidentified color
15106e82
BA
1183 }
1184
ca8a3993 1185 // Piece on i,j. '' if square is empty
41534b92 1186 getPiece(i, j) {
15106e82
BA
1187 if (typeof j == "string")
1188 return j; //reserves
41534b92
BA
1189 return this.board[i][j].charAt(1);
1190 }
1191
cc2c7183 1192 // Piece type on square (i,j)
6b9320bb 1193 getPieceType(x, y, p) {
65cf1690 1194 if (!p)
6b9320bb
BA
1195 p = this.getPiece(x, y);
1196 return this.pieces()[p].moveas || p;
1197 }
1198
1199 isKing(x, y, p) {
1200 if (!p)
1201 p = this.getPiece(x, y);
1202 if (!this.options["cannibal"])
1203 return p == 'k';
1204 return !!C.CannibalKings[p];
cc2c7183
BA
1205 }
1206
41534b92
BA
1207 // Get opponent color
1208 static GetOppCol(color) {
1209 return (color == "w" ? "b" : "w");
1210 }
1211
41534b92
BA
1212 // Is (x,y) on the chessboard?
1213 onBoard(x, y) {
b99ce1fb
BA
1214 return (x >= 0 && x < this.size.x &&
1215 y >= 0 && y < this.size.y);
41534b92
BA
1216 }
1217
15106e82 1218 // Am I allowed to move thing at square x,y ?
41534b92 1219 canIplay(x, y) {
0c44c676 1220 return (this.playerColor == this.turn && this.getColor(x, y) == this.turn);
41534b92
BA
1221 }
1222
1223 ////////////////////////
1224 // PIECES SPECIFICATIONS
1225
c9ab0340 1226 pieces(color, x, y) {
41534b92 1227 const pawnShift = (color == "w" ? -1 : 1);
9db5050a
BA
1228 // NOTE: jump 2 squares from first rank (pawns can be here sometimes)
1229 const initRank = ((color == 'w' && x >= 6) || (color == 'b' && x <= 1));
41534b92
BA
1230 return {
1231 'p': {
1232 "class": "pawn",
c9ab0340
BA
1233 moves: [
1234 {
1235 steps: [[pawnShift, 0]],
1236 range: (initRank ? 2 : 1)
1237 }
1238 ],
1239 attack: [
1240 {
1241 steps: [[pawnShift, 1], [pawnShift, -1]],
1242 range: 1
1243 }
1244 ]
41534b92 1245 },
41534b92
BA
1246 'r': {
1247 "class": "rook",
c9ab0340
BA
1248 moves: [
1249 {steps: [[0, 1], [0, -1], [1, 0], [-1, 0]]}
1250 ]
41534b92 1251 },
41534b92
BA
1252 'n': {
1253 "class": "knight",
c9ab0340
BA
1254 moves: [
1255 {
1256 steps: [
1257 [1, 2], [1, -2], [-1, 2], [-1, -2],
1258 [2, 1], [-2, 1], [2, -1], [-2, -1]
1259 ],
1260 range: 1
1261 }
1262 ]
41534b92 1263 },
41534b92
BA
1264 'b': {
1265 "class": "bishop",
c9ab0340
BA
1266 moves: [
1267 {steps: [[1, 1], [1, -1], [-1, 1], [-1, -1]]}
1268 ]
41534b92 1269 },
41534b92
BA
1270 'q': {
1271 "class": "queen",
c9ab0340
BA
1272 moves: [
1273 {
1274 steps: [
1275 [0, 1], [0, -1], [1, 0], [-1, 0],
1276 [1, 1], [1, -1], [-1, 1], [-1, -1]
1277 ]
1278 }
41534b92
BA
1279 ]
1280 },
41534b92
BA
1281 'k': {
1282 "class": "king",
c9ab0340
BA
1283 moves: [
1284 {
1285 steps: [
1286 [0, 1], [0, -1], [1, 0], [-1, 0],
1287 [1, 1], [1, -1], [-1, 1], [-1, -1]
1288 ],
1289 range: 1
1290 }
1291 ]
cc2c7183
BA
1292 },
1293 // Cannibal kings:
c9ab0340
BA
1294 '!': {"class": "king-pawn", moveas: "p"},
1295 '#': {"class": "king-rook", moveas: "r"},
1296 '$': {"class": "king-knight", moveas: "n"},
1297 '%': {"class": "king-bishop", moveas: "b"},
1298 '*': {"class": "king-queen", moveas: "q"}
41534b92
BA
1299 };
1300 }
1301
af9c9be3
BA
1302 // NOTE: using special symbols to not interfere with variants' pieces codes
1303 static get CannibalKings() {
1304 return {
1305 "!": "p",
1306 "#": "r",
1307 "$": "n",
1308 "%": "b",
1309 "*": "q",
1310 "k": "k"
1311 };
1312 }
1313
1314 static get CannibalKingCode() {
1315 return {
1316 "p": "!",
1317 "r": "#",
1318 "n": "$",
1319 "b": "%",
1320 "q": "*",
1321 "k": "k"
1322 };
1323 }
1324
1325 //////////////////////////
1326 // MOVES GENERATION UTILS
41534b92 1327
adf7c659
BA
1328 // For Cylinder: get Y coordinate
1329 getY(y) {
b4ae3ff6
BA
1330 if (!this.options["cylinder"])
1331 return y;
41534b92 1332 let res = y % this.size.y;
b4ae3ff6 1333 if (res < 0)
adf7c659 1334 res += this.size.y;
41534b92
BA
1335 return res;
1336 }
1337
ca8a3993
BA
1338 getSegments(curSeg, segStart, segEnd) {
1339 if (curSeg.length == 0)
1340 return undefined;
1341 let segments = JSON.parse(JSON.stringify(curSeg)); //not altering
1342 segments.push([[segStart[0], segStart[1]], [segEnd[0], segEnd[1]]]);
1343 return segments;
1344 }
1345
6b9320bb
BA
1346 getStepSpec(color, x, y, piece) {
1347 return this.pieces(color, x, y)[piece || this.getPieceType(x, y)];
ca8a3993
BA
1348 }
1349
af9c9be3
BA
1350 // Can thing on square1 capture thing on square2?
1351 canTake([x1, y1], [x2, y2]) {
1352 return this.getColor(x1, y1) !== this.getColor(x2, y2);
1353 }
1354
1355 canStepOver(i, j, p) {
1356 // In some variants, objects on boards don't stop movement (Chakart)
1357 return this.board[i][j] == "";
1358 }
1359
ca8a3993
BA
1360 canDrop([c, p], [i, j]) {
1361 return (
1362 this.board[i][j] == "" &&
1363 (!this.enlightened || this.enlightened[i][j]) &&
1364 (
1365 p != "p" ||
1366 (c == 'w' && i < this.size.x - 1) ||
1367 (c == 'b' && i > 0)
1368 )
1369 );
1370 }
1371
af9c9be3
BA
1372 // For Madrasi:
1373 // (redefined in Baroque etc, where Madrasi condition doesn't make sense)
1374 isImmobilized([x, y]) {
1375 if (!this.options["madrasi"])
1376 return false;
1377 const color = this.getColor(x, y);
1378 const oppCol = C.GetOppCol(color);
6b9320bb
BA
1379 const piece = this.getPieceType(x, y);
1380 const stepSpec = this.getStepSpec(color, x, y, piece);
af9c9be3
BA
1381 const attacks = stepSpec.attack || stepSpec.moves;
1382 for (let a of attacks) {
1383 outerLoop: for (let step of a.steps) {
1384 let [i, j] = [x + step[0], y + step[1]];
1385 let stepCounter = 1;
1386 while (this.onBoard(i, j) && this.board[i][j] == "") {
1387 if (a.range <= stepCounter++)
1388 continue outerLoop;
1389 i += step[0];
1390 j = this.getY(j + step[1]);
1391 }
1392 if (
1393 this.onBoard(i, j) &&
1394 this.getColor(i, j) == oppCol &&
1395 this.getPieceType(i, j) == piece
1396 ) {
1397 return true;
1398 }
1399 }
1400 }
1401 return false;
1402 }
1403
41534b92
BA
1404 // Stop at the first capture found
1405 atLeastOneCapture(color) {
cc2c7183 1406 const oppCol = C.GetOppCol(color);
6b9320bb
BA
1407 const allowed = (sq1, sq2) => {
1408 return (
1409 // NOTE: canTake is reversed for Zen.
1410 // Generally ok because of the symmetry. TODO?
1411 this.canTake(sq1, sq2) &&
1412 this.filterValid(
1413 [this.getBasicMove(sq1, sq2)]).length >= 1
1414 );
af9c9be3
BA
1415 };
1416 for (let i=0; i<this.size.x; i++) {
1417 for (let j=0; j<this.size.y; j++) {
1418 if (this.getColor(i, j) == color) {
1419 if (
6b9320bb
BA
1420 (
1421 !this.options["zen"] &&
1422 this.findDestSquares(
1423 [i, j],
1424 {
1425 attackOnly: true,
1426 one: true,
1427 segments: this.options["cylinder"]
1428 },
1429 allowed
1430 )
1431 )
1432 ||
1433 (
1434 (
1435 this.options["zen"] &&
1436 this.findCapturesOn(
1437 [i, j],
1438 {
1439 one: true,
1440 segments: this.options["cylinder"]
1441 },
1442 allowed
1443 )
1444 )
1445 )
af9c9be3
BA
1446 ) {
1447 return true;
41534b92
BA
1448 }
1449 }
1450 }
1451 }
1452 return false;
1453 }
1454
af9c9be3 1455 compatibleStep([x1, y1], [x2, y2], step, range) {
6b9320bb 1456 const epsilon = 1e-7; //arbitrary small value
af9c9be3
BA
1457 let shifts = [0];
1458 if (this.options["cylinder"])
1459 Array.prototype.push.apply(shifts, [-this.size.y, this.size.y]);
1460 for (let sh of shifts) {
1461 const rx = (x2 - x1) / step[0],
1462 ry = (y2 + sh - y1) / step[1];
1463 if (
6b9320bb 1464 // Zero step but non-zero interval => impossible
af9c9be3 1465 (!Number.isFinite(rx) && !Number.isNaN(rx)) ||
6b9320bb
BA
1466 (!Number.isFinite(ry) && !Number.isNaN(ry)) ||
1467 // Negative number of step (impossible)
1468 (rx < 0 || ry < 0) ||
1469 // Not the same number of steps in both directions:
1470 (!Number.isNaN(rx) && !Number.isNaN(ry) && Math.abs(rx - ry) > epsilon)
af9c9be3
BA
1471 ) {
1472 continue;
1473 }
1474 let distance = (Number.isNaN(rx) ? ry : rx);
6b9320bb 1475 if (Math.abs(distance - Math.round(distance)) > epsilon)
af9c9be3
BA
1476 continue;
1477 distance = Math.round(distance); //in case of (numerical...)
6b9320bb 1478 if (!range || range >= distance)
af9c9be3
BA
1479 return true;
1480 }
1481 return false;
1482 }
1483
1484 ////////////////////
1485 // MOVES GENERATION
1486
41534b92
BA
1487 getDropMovesFrom([c, p]) {
1488 // NOTE: by design, this.reserve[c][p] >= 1 on user click
1a7c0492 1489 // (but not necessarily otherwise: atLeastOneMove() etc)
b4ae3ff6
BA
1490 if (this.reserve[c][p] == 0)
1491 return [];
41534b92
BA
1492 let moves = [];
1493 for (let i=0; i<this.size.x; i++) {
1494 for (let j=0; j<this.size.y; j++) {
9b760538 1495 if (this.onBoard(i, j) && this.canDrop([c, p], [i, j])) {
ca8a3993
BA
1496 let mv = new Move({
1497 start: {x: c, y: p},
1498 end: {x: i, y: j},
1499 appear: [new PiPo({x: i, y: j, c: c, p: p})],
1500 vanish: []
1501 });
1502 if (this.board[i][j] != "") {
1503 mv.vanish.push(new PiPo({
1504 x: i,
1505 y: j,
1506 c: this.getColor(i, j),
1507 p: this.getPiece(i, j)
1508 }));
1509 }
1510 moves.push(mv);
41534b92
BA
1511 }
1512 }
1513 }
1514 return moves;
1515 }
1516
1517 // All possible moves from selected square
ca8a3993 1518 getPotentialMovesFrom([x, y], color) {
8b301184
BA
1519 if (this.subTurnTeleport == 2)
1520 return [];
ca8a3993
BA
1521 if (typeof x == "string")
1522 return this.getDropMovesFrom([x, y]);
1523 if (this.isImmobilized([x, y]))
b4ae3ff6 1524 return [];
ca8a3993
BA
1525 const piece = this.getPieceType(x, y);
1526 let moves = this.getPotentialMovesOf(piece, [x, y]);
1527 if (piece == "p" && this.hasEnpassant && this.epSquare)
1528 Array.prototype.push.apply(moves, this.getEnpassantCaptures([x, y]));
41534b92 1529 if (
a548cb4e 1530 this.isKing(0, 0, piece) && this.hasCastle &&
41534b92
BA
1531 this.castleFlags[color || this.turn].some(v => v < this.size.y)
1532 ) {
ca8a3993 1533 Array.prototype.push.apply(moves, this.getCastleMoves([x, y]));
41534b92
BA
1534 }
1535 return this.postProcessPotentialMoves(moves);
1536 }
1537
1538 postProcessPotentialMoves(moves) {
b4ae3ff6
BA
1539 if (moves.length == 0)
1540 return [];
41534b92 1541 const color = this.getColor(moves[0].start.x, moves[0].start.y);
cc2c7183 1542 const oppCol = C.GetOppCol(color);
41534b92 1543
6b9320bb 1544 if (this.options["capture"] && this.atLeastOneCapture(color))
57b8015b 1545 moves = this.capturePostProcess(moves, oppCol);
41534b92 1546
57b8015b 1547 if (this.options["atomic"])
98d14451 1548 moves = this.atomicPostProcess(moves, color, oppCol);
cc2c7183 1549
c9ab0340
BA
1550 if (
1551 moves.length > 0 &&
1552 this.getPieceType(moves[0].start.x, moves[0].start.y) == "p"
1553 ) {
98d14451 1554 moves = this.pawnPostProcess(moves, color, oppCol);
c9ab0340
BA
1555 }
1556
6b9320bb 1557 if (this.options["cannibal"] && this.options["rifle"])
cc2c7183 1558 // In this case a rifle-capture from last rank may promote a pawn
98d14451 1559 moves = this.riflePromotePostProcess(moves, color);
57b8015b
BA
1560
1561 return moves;
1562 }
1563
1564 capturePostProcess(moves, oppCol) {
1565 // Filter out non-capturing moves (not using m.vanish because of
1566 // self captures of Recycle and Teleport).
1567 return moves.filter(m => {
1568 return (
1569 this.board[m.end.x][m.end.y] != "" &&
1570 this.getColor(m.end.x, m.end.y) == oppCol
1571 );
1572 });
1573 }
1574
e7d409fc 1575 atomicPostProcess(moves, color, oppCol) {
57b8015b
BA
1576 moves.forEach(m => {
1577 if (
1578 this.board[m.end.x][m.end.y] != "" &&
1579 this.getColor(m.end.x, m.end.y) == oppCol
1580 ) {
1581 // Explosion!
1582 let steps = [
1583 [-1, -1],
1584 [-1, 0],
1585 [-1, 1],
1586 [0, -1],
1587 [0, 1],
1588 [1, -1],
1589 [1, 0],
1590 [1, 1]
1591 ];
e7d409fc
BA
1592 let mNext = new Move({
1593 start: m.end,
1594 end: m.end,
1595 appear: [],
1596 vanish: []
1597 });
57b8015b
BA
1598 for (let step of steps) {
1599 let x = m.end.x + step[0];
d262cff4 1600 let y = this.getY(m.end.y + step[1]);
57b8015b
BA
1601 if (
1602 this.onBoard(x, y) &&
1603 this.board[x][y] != "" &&
e7d409fc 1604 (x != m.start.x || y != m.start.y) &&
57b8015b
BA
1605 this.getPieceType(x, y) != "p"
1606 ) {
e7d409fc 1607 mNext.vanish.push(
57b8015b
BA
1608 new PiPo({
1609 p: this.getPiece(x, y),
1610 c: this.getColor(x, y),
1611 x: x,
1612 y: y
1613 })
1614 );
1615 }
1616 }
e7d409fc
BA
1617 if (!this.options["rifle"]) {
1618 // The moving piece also vanish
1619 mNext.vanish.unshift(
1620 new PiPo({
1621 x: m.end.x,
1622 y: m.end.y,
1623 c: color,
1624 p: this.getPiece(m.start.x, m.start.y)
1625 })
1626 );
1627 }
1628 m.next = mNext;
57b8015b
BA
1629 }
1630 });
98d14451 1631 return moves;
57b8015b
BA
1632 }
1633
1634 pawnPostProcess(moves, color, oppCol) {
1635 let moreMoves = [];
1636 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1637 const initPiece = this.getPiece(moves[0].start.x, moves[0].start.y);
1638 moves.forEach(m => {
57b8015b
BA
1639 const [x1, y1] = [m.start.x, m.start.y];
1640 const [x2, y2] = [m.end.x, m.end.y];
1641 const promotionOk = (
1642 x2 == lastRank &&
1643 (!this.options["rifle"] || this.board[x2][y2] == "")
1644 );
1645 if (!promotionOk)
1646 return; //nothing to do
8cc2f6d0
BA
1647 if (this.options["pawnfall"]) {
1648 m.appear.shift();
8cc2f6d0
BA
1649 return;
1650 }
9ac67217 1651 let finalPieces;
99ea2453
BA
1652 if (
1653 this.options["cannibal"] &&
1654 this.board[x2][y2] != "" &&
1655 this.getColor(x2, y2) == oppCol
1656 ) {
1657 finalPieces = [this.getPieceType(x2, y2)];
1658 }
1659 else
1660 finalPieces = this.pawnPromotions;
57b8015b
BA
1661 m.appear[0].p = finalPieces[0];
1662 if (initPiece == "!") //cannibal king-pawn
1663 m.appear[0].p = C.CannibalKingCode[finalPieces[0]];
1664 for (let i=1; i<finalPieces.length; i++) {
9ac67217 1665 let newMove = JSON.parse(JSON.stringify(m));
57b8015b 1666 const piece = finalPieces[i];
9ac67217 1667 m.appear[0].p = (initPiece != "!" ? piece : C.CannibalKingCode[piece]);
57b8015b
BA
1668 moreMoves.push(newMove);
1669 }
1670 });
98d14451 1671 return moves.concat(moreMoves);
57b8015b 1672 }
cc2c7183 1673
9db5050a 1674 riflePromotePostProcess(moves, color) {
57b8015b
BA
1675 const lastRank = (color == "w" ? 0 : this.size.x - 1);
1676 let newMoves = [];
1677 moves.forEach(m => {
1678 if (
1679 m.start.x == lastRank &&
1680 m.appear.length >= 1 &&
1681 m.appear[0].p == "p" &&
1682 m.appear[0].x == m.start.x &&
1683 m.appear[0].y == m.start.y
1684 ) {
57b8015b
BA
1685 m.appear[0].p = this.pawnPromotions[0];
1686 for (let i=1; i<this.pawnPromotions.length; i++) {
1687 let newMv = JSON.parse(JSON.stringify(m));
1688 newMv.appear[0].p = this.pawnSpecs.promotions[i];
1689 newMoves.push(newMv);
1690 }
1691 }
1692 });
98d14451 1693 return moves.concat(newMoves);
41534b92
BA
1694 }
1695
af9c9be3 1696 // Generic method to find possible moves of "sliding or jumping" pieces
6b9320bb 1697 getPotentialMovesOf(piece, [x, y]) {
41534b92 1698 const color = this.getColor(x, y);
6b9320bb 1699 const stepSpec = this.getStepSpec(color, x, y, piece);
af9c9be3 1700 let squares = [];
6b9320bb 1701 if (stepSpec.attack) {
af9c9be3
BA
1702 squares = this.findDestSquares(
1703 [x, y],
1704 {
1705 attackOnly: true,
6b9320bb
BA
1706 segments: this.options["cylinder"],
1707 stepSpec: stepSpec
af9c9be3 1708 },
6b9320bb 1709 ([i1, j1], [i2, j2]) => {
af9c9be3 1710 return (
6b9320bb
BA
1711 (!this.options["zen"] || this.isKing(i2, j2)) &&
1712 this.canTake([i1, j1], [i2, j2])
af9c9be3 1713 );
c9ab0340 1714 }
af9c9be3
BA
1715 );
1716 }
1717 const noSpecials = this.findDestSquares(
1718 [x, y],
1719 {
6b9320bb
BA
1720 moveOnly: !!stepSpec.attack || this.options["zen"],
1721 segments: this.options["cylinder"],
1722 stepSpec: stepSpec
1723 }
af9c9be3
BA
1724 );
1725 Array.prototype.push.apply(squares, noSpecials);
1726 if (this.options["zen"]) {
1727 let zenCaptures = this.findCapturesOn(
1728 [x, y],
6b9320bb
BA
1729 {}, //byCol: default is ok
1730 ([i1, j1], [i2, j2]) =>
1731 !this.isKing(i1, j1) && this.canTake([i2, j2], [i1, j1])
af9c9be3
BA
1732 );
1733 // Technical step: segments (if any) are reversed
1734 if (this.options["cylinder"]) {
1735 zenCaptures.forEach(z => {
ca8a3993 1736 z.segments = z.segments.reverse().map(s => s.reverse())
af9c9be3 1737 });
41534b92 1738 }
af9c9be3 1739 Array.prototype.push.apply(squares, zenCaptures);
41534b92 1740 }
af9c9be3
BA
1741 if (
1742 this.options["recycle"] ||
1743 (this.options["teleport"] && this.subTurnTeleport == 1)
1744 ) {
1745 const selfCaptures = this.findDestSquares(
1746 [x, y],
1747 {
1748 attackOnly: true,
6b9320bb
BA
1749 segments: this.options["cylinder"],
1750 stepSpec: stepSpec
af9c9be3 1751 },
6b9320bb
BA
1752 ([i1, j1], [i2, j2]) =>
1753 this.getColor(i2, j2) == color && !this.isKing(i2, j2)
af9c9be3
BA
1754 );
1755 Array.prototype.push.apply(squares, selfCaptures);
1756 }
1757 return squares.map(s => {
1758 let mv = this.getBasicMove([x, y], s.sq);
1759 if (this.options["cylinder"] && s.segments.length >= 2)
1760 mv.segments = s.segments;
1761 return mv;
1762 });
3b641716
BA
1763 }
1764
af9c9be3
BA
1765 findDestSquares([x, y], o, allowed) {
1766 if (!allowed)
6b9320bb 1767 allowed = (sq1, sq2) => this.canTake(sq1, sq2);
65cf1690 1768 const apparentPiece = this.getPiece(x, y); //how it looks
af9c9be3
BA
1769 let res = [];
1770 // Next 3 for Cylinder mode: (unused if !o.segments)
adf7c659
BA
1771 let explored = {};
1772 let segments = [];
1773 let segStart = [];
af9c9be3
BA
1774 const addSquare = ([i, j]) => {
1775 let elt = {sq: [i, j]};
1776 if (o.segments)
1777 elt.segments = this.getSegments(segments, segStart, end);
1778 res.push(elt);
adf7c659 1779 };
af9c9be3 1780 const exploreSteps = (stepArray) => {
c9ab0340
BA
1781 for (let s of stepArray) {
1782 outerLoop: for (let step of s.steps) {
af9c9be3
BA
1783 if (o.segments) {
1784 segments = [];
1785 segStart = [x, y];
1786 }
d262cff4
BA
1787 let [i, j] = [x, y];
1788 let stepCounter = 0;
1789 while (
1790 this.onBoard(i, j) &&
65cf1690 1791 ((i == x && j == y) || this.canStepOver(i, j, apparentPiece))
d262cff4 1792 ) {
6b9320bb 1793 if (!explored[i + "." + j] && (i != x || j != y)) {
c9ab0340 1794 explored[i + "." + j] = true;
af9c9be3 1795 if (
6b9320bb
BA
1796 !o.captureTarget ||
1797 (o.captureTarget[0] == i && o.captureTarget[1] == j)
af9c9be3
BA
1798 ) {
1799 if (o.one && !o.attackOnly)
1800 return true;
1801 if (!o.attackOnly)
1802 addSquare(!o.captureTarget ? [i, j] : [x, y]);
1803 if (o.captureTarget)
1804 return res[0];
1805 }
c9ab0340
BA
1806 }
1807 if (s.range <= stepCounter++)
1808 continue outerLoop;
d262cff4 1809 const oldIJ = [i, j];
c9ab0340 1810 i += step[0];
adf7c659 1811 j = this.getY(j + step[1]);
af9c9be3 1812 if (o.segments && Math.abs(j - oldIJ[1]) > 1) {
d262cff4 1813 // Boundary between segments (cylinder mode)
adf7c659
BA
1814 segments.push([[segStart[0], segStart[1]], oldIJ]);
1815 segStart = [i, j];
d262cff4 1816 }
c9ab0340
BA
1817 }
1818 if (!this.onBoard(i, j))
1819 continue;
1820 const pieceIJ = this.getPieceType(i, j);
af9c9be3 1821 if (!explored[i + "." + j]) {
c9ab0340 1822 explored[i + "." + j] = true;
6b9320bb 1823 if (allowed([x, y], [i, j])) {
af9c9be3
BA
1824 if (o.one && !o.moveOnly)
1825 return true;
1826 if (!o.moveOnly)
1827 addSquare(!o.captureTarget ? [i, j] : [x, y]);
1828 if (
1829 o.captureTarget &&
1830 o.captureTarget[0] == i && o.captureTarget[1] == j
1831 ) {
1832 return res[0];
1833 }
1834 }
c9ab0340
BA
1835 }
1836 }
41534b92 1837 }
6b9320bb 1838 return undefined; //default, but let's explicit it
c9ab0340 1839 };
af9c9be3 1840 if (o.captureTarget)
6b9320bb 1841 return exploreSteps(o.captureSteps)
af9c9be3 1842 else {
6b9320bb
BA
1843 const stepSpec =
1844 o.stepSpec || this.getStepSpec(this.getColor(x, y), x, y);
1845 let outOne = false;
af9c9be3 1846 if (!o.attackOnly || !stepSpec.attack)
6b9320bb
BA
1847 outOne = exploreSteps(stepSpec.moves);
1848 if (!outOne && !o.moveOnly && !!stepSpec.attack) {
1849 o.attackOnly = true; //ok because o is always a temporary object
1850 outOne = exploreSteps(stepSpec.attack);
1851 }
1852 return (o.one ? outOne : res);
082e639a 1853 }
41534b92
BA
1854 }
1855
082e639a 1856 // Search for enemy (or not) pieces attacking [x, y]
af9c9be3 1857 findCapturesOn([x, y], o, allowed) {
af9c9be3
BA
1858 if (!o.byCol)
1859 o.byCol = [C.GetOppCol(this.getColor(x, y) || this.turn)];
ca8a3993 1860 let res = [];
c9ab0340
BA
1861 for (let i=0; i<this.size.x; i++) {
1862 for (let j=0; j<this.size.y; j++) {
af9c9be3 1863 const colIJ = this.getColor(i, j);
57b8015b
BA
1864 if (
1865 this.board[i][j] != "" &&
af9c9be3 1866 o.byCol.includes(colIJ) &&
57b8015b
BA
1867 !this.isImmobilized([i, j])
1868 ) {
65cf1690
BA
1869 const apparentPiece = this.getPiece(i, j);
1870 // Quick check: does this potential attacker target x,y ?
1871 if (this.canStepOver(x, y, apparentPiece))
1872 continue;
af9c9be3 1873 const stepSpec = this.getStepSpec(colIJ, i, j);
c9ab0340
BA
1874 const attacks = stepSpec.attack || stepSpec.moves;
1875 for (let a of attacks) {
1876 for (let s of a.steps) {
1877 // Quick check: if step isn't compatible, don't even try
af9c9be3 1878 if (!this.compatibleStep([i, j], [x, y], s, a.range))
c9ab0340
BA
1879 continue;
1880 // Finally verify that nothing stand in-between
6b9320bb 1881 const out = this.findDestSquares(
af9c9be3
BA
1882 [i, j],
1883 {
1884 captureTarget: [x, y],
1885 captureSteps: [{steps: [s], range: a.range}],
6b9320bb
BA
1886 segments: o.segments,
1887 attackOnly: true,
1888 one: false //one and captureTarget are mutually exclusive
af9c9be3 1889 },
6b9320bb 1890 allowed
af9c9be3 1891 );
6b9320bb 1892 if (out) {
af9c9be3
BA
1893 if (o.one)
1894 return true;
6b9320bb 1895 res.push(out);
c9ab0340
BA
1896 }
1897 }
1898 }
41534b92 1899 }
c9ab0340
BA
1900 }
1901 }
6b9320bb 1902 return (o.one ? false : res);
57b8015b
BA
1903 }
1904
41534b92
BA
1905 // Build a regular move from its initial and destination squares.
1906 // tr: transformation
1907 getBasicMove([sx, sy], [ex, ey], tr) {
1908 const initColor = this.getColor(sx, sy);
cc2c7183 1909 const initPiece = this.getPiece(sx, sy);
41534b92
BA
1910 const destColor = (this.board[ex][ey] != "" ? this.getColor(ex, ey) : "");
1911 let mv = new Move({
1912 appear: [],
1913 vanish: [],
15106e82
BA
1914 start: {x: sx, y: sy},
1915 end: {x: ex, y: ey}
41534b92
BA
1916 });
1917 if (
1918 !this.options["rifle"] ||
1919 this.board[ex][ey] == "" ||
1920 destColor == initColor //Recycle, Teleport
1921 ) {
1922 mv.appear = [
1923 new PiPo({
1924 x: ex,
1925 y: ey,
1926 c: !!tr ? tr.c : initColor,
1927 p: !!tr ? tr.p : initPiece
1928 })
1929 ];
1930 mv.vanish = [
1931 new PiPo({
1932 x: sx,
1933 y: sy,
1934 c: initColor,
1935 p: initPiece
1936 })
1937 ];
1938 }
1939 if (this.board[ex][ey] != "") {
1940 mv.vanish.push(
1941 new PiPo({
1942 x: ex,
1943 y: ey,
1944 c: this.getColor(ex, ey),
cc2c7183 1945 p: this.getPiece(ex, ey)
41534b92
BA
1946 })
1947 );
41534b92 1948 if (this.options["cannibal"] && destColor != initColor) {
6b9320bb 1949 const lastIdx = mv.vanish.length - 1; //think "Rifle+Cannibal"
cc2c7183 1950 let trPiece = mv.vanish[lastIdx].p;
6b9320bb 1951 if (this.isKing(sx, sy))
cc2c7183 1952 trPiece = C.CannibalKingCode[trPiece];
b4ae3ff6
BA
1953 if (mv.appear.length >= 1)
1954 mv.appear[0].p = trPiece;
41534b92
BA
1955 else if (this.options["rifle"]) {
1956 mv.appear.unshift(
1957 new PiPo({
1958 x: sx,
1959 y: sy,
1960 c: initColor,
cc2c7183 1961 p: trPiece
41534b92
BA
1962 })
1963 );
1964 mv.vanish.unshift(
1965 new PiPo({
1966 x: sx,
1967 y: sy,
1968 c: initColor,
1969 p: initPiece
1970 })
1971 );
1972 }
1973 }
1974 }
1975 return mv;
1976 }
1977
1978 // En-passant square, if any
1979 getEpSquare(moveOrSquare) {
1980 if (typeof moveOrSquare === "string") {
1981 const square = moveOrSquare;
b4ae3ff6
BA
1982 if (square == "-")
1983 return undefined;
cc2c7183 1984 return C.SquareToCoords(square);
41534b92
BA
1985 }
1986 // Argument is a move:
1987 const move = moveOrSquare;
1988 const s = move.start,
1989 e = move.end;
1990 if (
1991 s.y == e.y &&
1992 Math.abs(s.x - e.x) == 2 &&
1993 // Next conditions for variants like Atomic or Rifle, Recycle...
65cf1690
BA
1994 (
1995 move.appear.length > 0 &&
ca8a3993 1996 this.getPieceType(0, 0, move.appear[0].p) == 'p'
65cf1690
BA
1997 )
1998 &&
1999 (
2000 move.vanish.length > 0 &&
ca8a3993 2001 this.getPieceType(0, 0, move.vanish[0].p) == 'p'
65cf1690 2002 )
41534b92
BA
2003 ) {
2004 return {
2005 x: (s.x + e.x) / 2,
2006 y: s.y
2007 };
2008 }
2009 return undefined; //default
2010 }
2011
2012 // Special case of en-passant captures: treated separately
c9ab0340 2013 getEnpassantCaptures([x, y]) {
41534b92 2014 const color = this.getColor(x, y);
c9ab0340 2015 const shiftX = (color == 'w' ? -1 : 1);
cc2c7183 2016 const oppCol = C.GetOppCol(color);
41534b92 2017 if (
ca8a3993 2018 this.epSquare &&
41534b92 2019 this.epSquare.x == x + shiftX &&
d262cff4 2020 Math.abs(this.getY(this.epSquare.y - y)) == 1 &&
ca8a3993
BA
2021 // Doublemove (and Progressive?) guards:
2022 this.board[this.epSquare.x][this.epSquare.y] == "" &&
2023 this.getColor(x, this.epSquare.y) == oppCol
41534b92
BA
2024 ) {
2025 const [epx, epy] = [this.epSquare.x, this.epSquare.y];
ca8a3993
BA
2026 this.board[epx][epy] = oppCol + 'p';
2027 let enpassantMove = this.getBasicMove([x, y], [epx, epy]);
41534b92
BA
2028 this.board[epx][epy] = "";
2029 const lastIdx = enpassantMove.vanish.length - 1; //think Rifle
2030 enpassantMove.vanish[lastIdx].x = x;
ca8a3993 2031 return [enpassantMove];
41534b92 2032 }
ca8a3993 2033 return [];
41534b92
BA
2034 }
2035
ca8a3993 2036 getCastleMoves([x, y], finalSquares, castleWith) {
41534b92
BA
2037 const c = this.getColor(x, y);
2038
2039 // Castling ?
cc2c7183 2040 const oppCol = C.GetOppCol(c);
41534b92
BA
2041 let moves = [];
2042 // King, then rook:
2043 finalSquares =
2044 finalSquares || [ [2, 3], [this.size.y - 2, this.size.y - 3] ];
cc2c7183 2045 const castlingKing = this.getPiece(x, y);
41534b92
BA
2046 castlingCheck: for (
2047 let castleSide = 0;
2048 castleSide < 2;
2049 castleSide++ //large, then small
2050 ) {
b4ae3ff6
BA
2051 if (this.castleFlags[c][castleSide] >= this.size.y)
2052 continue;
41534b92
BA
2053 // If this code is reached, rook and king are on initial position
2054
2055 // NOTE: in some variants this is not a rook
2056 const rookPos = this.castleFlags[c][castleSide];
cc2c7183 2057 const castlingPiece = this.getPiece(x, rookPos);
41534b92
BA
2058 if (
2059 this.board[x][rookPos] == "" ||
2060 this.getColor(x, rookPos) != c ||
ca8a3993 2061 (castleWith && !castleWith.includes(castlingPiece))
41534b92
BA
2062 ) {
2063 // Rook is not here, or changed color (see Benedict)
2064 continue;
2065 }
2066 // Nothing on the path of the king ? (and no checks)
2067 const finDist = finalSquares[castleSide][0] - y;
2068 let step = finDist / Math.max(1, Math.abs(finDist));
2069 let i = y;
2070 do {
2071 if (
ca8a3993
BA
2072 // NOTE: next weird test because underCheck() verification
2073 // will be executed in filterValid() later.
2074 (
2075 i != finalSquares[castleSide][0] &&
2076 this.underCheck([x, i], oppCol)
2077 )
2078 ||
41534b92
BA
2079 (
2080 this.board[x][i] != "" &&
2081 // NOTE: next check is enough, because of chessboard constraints
2082 (this.getColor(x, i) != c || ![rookPos, y].includes(i))
2083 )
2084 ) {
2085 continue castlingCheck;
2086 }
2087 i += step;
2088 } while (i != finalSquares[castleSide][0]);
2089 // Nothing on the path to the rook?
2090 step = (castleSide == 0 ? -1 : 1);
2091 for (i = y + step; i != rookPos; i += step) {
b4ae3ff6
BA
2092 if (this.board[x][i] != "")
2093 continue castlingCheck;
41534b92
BA
2094 }
2095
2096 // Nothing on final squares, except maybe king and castling rook?
2097 for (i = 0; i < 2; i++) {
2098 if (
2099 finalSquares[castleSide][i] != rookPos &&
2100 this.board[x][finalSquares[castleSide][i]] != "" &&
2101 (
2102 finalSquares[castleSide][i] != y ||
2103 this.getColor(x, finalSquares[castleSide][i]) != c
2104 )
2105 ) {
2106 continue castlingCheck;
2107 }
2108 }
2109
ca8a3993 2110 // If this code is reached, castle is potentially valid
41534b92
BA
2111 moves.push(
2112 new Move({
2113 appear: [
2114 new PiPo({
2115 x: x,
2116 y: finalSquares[castleSide][0],
2117 p: castlingKing,
2118 c: c
2119 }),
2120 new PiPo({
2121 x: x,
2122 y: finalSquares[castleSide][1],
2123 p: castlingPiece,
2124 c: c
2125 })
2126 ],
2127 vanish: [
2128 // King might be initially disguised (Titan...)
2129 new PiPo({ x: x, y: y, p: castlingKing, c: c }),
2130 new PiPo({ x: x, y: rookPos, p: castlingPiece, c: c })
2131 ],
2132 end:
2133 Math.abs(y - rookPos) <= 2
c9ab0340
BA
2134 ? {x: x, y: rookPos}
2135 : {x: x, y: y + 2 * (castleSide == 0 ? -1 : 1)}
41534b92
BA
2136 })
2137 );
2138 }
2139
2140 return moves;
2141 }
2142
2143 ////////////////////
2144 // MOVES VALIDATION
2145
af9c9be3
BA
2146 // Is piece (or square) at given position attacked by "oppCol" ?
2147 underAttack([x, y], oppCol) {
6b9320bb
BA
2148 // An empty square is considered as king,
2149 // since it's used only in getCastleMoves (TODO?)
2150 const king = this.board[x][y] == "" || this.isKing(x, y);
af9c9be3
BA
2151 return (
2152 (
2153 (!this.options["zen"] || king) &&
6b9320bb
BA
2154 this.findCapturesOn(
2155 [x, y],
2156 {
2157 byCol: [oppCol],
2158 segments: this.options["cylinder"],
2159 one: true
2160 }
2161 )
af9c9be3
BA
2162 )
2163 ||
2164 (
6b9320bb
BA
2165 (!!this.options["zen"] && !king) &&
2166 this.findDestSquares(
2167 [x, y],
2168 {
2169 attackOnly: true,
2170 segments: this.options["cylinder"],
2171 one: true
2172 },
2173 ([i1, j1], [i2, j2]) => this.getColor(i2, j2) == oppCol
2174 )
af9c9be3
BA
2175 )
2176 );
2177 }
2178
f3e90e30 2179 // Argument is (very generally) an array of squares (= arrays)
a548cb4e 2180 underCheck(square_s, oppCol) {
b4ae3ff6
BA
2181 if (this.options["taking"] || this.options["dark"])
2182 return false;
f3e90e30 2183 if (!Array.isArray(square_s[0]))
a548cb4e
BA
2184 square_s = [square_s];
2185 return square_s.some(sq => this.underAttack(sq, oppCol));
41534b92
BA
2186 }
2187
a548cb4e 2188 // Scan board for king(s)
41534b92 2189 searchKingPos(color) {
a548cb4e 2190 let res = [];
41534b92
BA
2191 for (let i=0; i < this.size.x; i++) {
2192 for (let j=0; j < this.size.y; j++) {
6b9320bb 2193 if (this.getColor(i, j) == color && this.isKing(i, j))
a548cb4e 2194 res.push([i, j]);
41534b92
BA
2195 }
2196 }
a548cb4e 2197 return res;
41534b92
BA
2198 }
2199
af9c9be3 2200 // 'color' arg because some variants (e.g. Refusal) check opponent moves
f5435757 2201 filterValid(moves, color) {
f5435757
BA
2202 if (!color)
2203 color = this.turn;
cc2c7183 2204 const oppCol = C.GetOppCol(color);
a548cb4e 2205 let kingPos = this.searchKingPos(color);
41534b92
BA
2206 let filtered = {}; //avoid re-checking similar moves (promotions...)
2207 return moves.filter(m => {
2208 const key = m.start.x + m.start.y + '.' + m.end.x + m.end.y;
2209 if (!filtered[key]) {
2210 this.playOnBoard(m);
a548cb4e
BA
2211 let newKingPP = null,
2212 sqIdx = 0,
41534b92 2213 res = true; //a priori valid
f3e90e30
BA
2214 const oldKingPP =
2215 m.vanish.find(v => this.isKing(0, 0, v.p) && v.c == color);
a548cb4e 2216 if (oldKingPP) {
41534b92 2217 // Search king in appear array:
a548cb4e
BA
2218 newKingPP =
2219 m.appear.find(a => this.isKing(0, 0, a.p) && a.c == color);
2220 if (newKingPP) {
f3e90e30
BA
2221 sqIdx = kingPos.findIndex(kp =>
2222 kp[0] == oldKingPP.x && kp[1] == oldKingPP.y);
a548cb4e
BA
2223 kingPos[sqIdx] = [newKingPP.x, newKingPP.y];
2224 }
b4ae3ff6 2225 else
a548cb4e 2226 res = false; //king vanished
41534b92 2227 }
f3e90e30 2228 res &&= !this.underCheck(kingPos, oppCol);
a548cb4e
BA
2229 if (oldKingPP && newKingPP)
2230 kingPos[sqIdx] = [oldKingPP.x, oldKingPP.y];
41534b92
BA
2231 this.undoOnBoard(m);
2232 filtered[key] = res;
2233 return res;
2234 }
2235 return filtered[key];
2236 });
2237 }
2238
2239 /////////////////
2240 // MOVES PLAYING
2241
41534b92
BA
2242 // Apply a move on board
2243 playOnBoard(move) {
6997e386
BA
2244 for (let psq of move.vanish)
2245 this.board[psq.x][psq.y] = "";
2246 for (let psq of move.appear)
2247 this.board[psq.x][psq.y] = psq.c + psq.p;
41534b92
BA
2248 }
2249 // Un-apply the played move
2250 undoOnBoard(move) {
6997e386
BA
2251 for (let psq of move.appear)
2252 this.board[psq.x][psq.y] = "";
2253 for (let psq of move.vanish)
2254 this.board[psq.x][psq.y] = psq.c + psq.p;
41534b92
BA
2255 }
2256
2257 updateCastleFlags(move) {
2258 // Update castling flags if start or arrive from/at rook/king locations
2259 move.appear.concat(move.vanish).forEach(psq => {
6b9320bb 2260 if (this.isKing(0, 0, psq.p))
41534b92 2261 this.castleFlags[psq.c] = [this.size.y, this.size.y];
41534b92 2262 // NOTE: not "else if" because king can capture enemy rook...
cc2c7183 2263 let c = "";
b4ae3ff6
BA
2264 if (psq.x == 0)
2265 c = "b";
2266 else if (psq.x == this.size.x - 1)
2267 c = "w";
cc2c7183 2268 if (c != "") {
41534b92 2269 const fidx = this.castleFlags[c].findIndex(f => f == psq.y);
b4ae3ff6
BA
2270 if (fidx >= 0)
2271 this.castleFlags[c][fidx] = this.size.y;
41534b92
BA
2272 }
2273 });
2274 }
2275
2276 prePlay(move) {
2277 if (
99ea2453
BA
2278 this.hasCastle &&
2279 // If flags already off, no need to re-check:
ca8a3993
BA
2280 Object.values(this.castleFlags).some(cvals =>
2281 cvals.some(val => val < this.size.y))
41534b92 2282 ) {
99ea2453
BA
2283 this.updateCastleFlags(move);
2284 }
2285 if (this.options["crazyhouse"]) {
2286 move.vanish.forEach(v => {
2287 const square = C.CoordsToSquare({x: v.x, y: v.y});
2288 if (this.ispawn[square])
2289 delete this.ispawn[square];
2290 });
2291 if (move.appear.length > 0 && move.vanish.length > 0) {
2292 // Assumption: something is moving
2293 const initSquare = C.CoordsToSquare(move.start);
f429756d 2294 const destSquare = C.CoordsToSquare(move.end);
99ea2453
BA
2295 if (
2296 this.ispawn[initSquare] ||
ca8a3993 2297 (move.vanish[0].p == 'p' && move.appear[0].p != 'p')
41534b92 2298 ) {
f429756d
BA
2299 this.ispawn[destSquare] = true;
2300 }
2301 else if (
2302 this.ispawn[destSquare] &&
2303 this.getColor(move.end.x, move.end.y) != move.vanish[0].c
2304 ) {
ca8a3993 2305 move.vanish[1].p = 'p';
f429756d 2306 delete this.ispawn[destSquare];
41534b92
BA
2307 }
2308 }
2309 }
2310 const minSize = Math.min(move.appear.length, move.vanish.length);
0c44c676
BA
2311 if (
2312 this.hasReserve &&
2313 // Warning; atomic pawn removal isn't a capture
2314 (!this.options["atomic"] || !this.rempawn || this.movesCount >= 1)
2315 ) {
41534b92
BA
2316 const color = this.turn;
2317 for (let i=minSize; i<move.appear.length; i++) {
2318 // Something appears = dropped on board (some exceptions, Chakart...)
0c44c676
BA
2319 if (move.appear[i].c == color) {
2320 const piece = move.appear[i].p;
2321 this.updateReserve(color, piece, this.reserve[color][piece] - 1);
2322 }
41534b92
BA
2323 }
2324 for (let i=minSize; i<move.vanish.length; i++) {
2325 // Something vanish: add to reserve except if recycle & opponent
0c44c676
BA
2326 if (
2327 this.options["crazyhouse"] ||
2328 (this.options["recycle"] && move.vanish[i].c == color)
2329 ) {
2330 const piece = move.vanish[i].p;
41534b92 2331 this.updateReserve(color, piece, this.reserve[color][piece] + 1);
0c44c676 2332 }
41534b92
BA
2333 }
2334 }
2335 }
2336
2337 play(move) {
2338 this.prePlay(move);
b4ae3ff6
BA
2339 if (this.hasEnpassant)
2340 this.epSquare = this.getEpSquare(move);
41534b92
BA
2341 this.playOnBoard(move);
2342 this.postPlay(move);
2343 }
2344
2345 postPlay(move) {
2346 const color = this.turn;
b4ae3ff6 2347 if (this.options["dark"])
c9ab0340 2348 this.updateEnlightened();
41534b92
BA
2349 if (this.options["teleport"]) {
2350 if (
cc2c7183 2351 this.subTurnTeleport == 1 &&
41534b92 2352 move.vanish.length > move.appear.length &&
af9c9be3 2353 move.vanish[1].c == color
41534b92
BA
2354 ) {
2355 const v = move.vanish[move.vanish.length - 1];
2356 this.captured = {x: v.x, y: v.y, c: v.c, p: v.p};
cc2c7183 2357 this.subTurnTeleport = 2;
41534b92
BA
2358 return;
2359 }
cc2c7183 2360 this.subTurnTeleport = 1;
41534b92
BA
2361 this.captured = null;
2362 }
5f08c59b 2363 if (this.isLastMove(move)) {
6b9320bb 2364 this.turn = C.GetOppCol(color);
5f08c59b
BA
2365 this.movesCount++;
2366 this.subTurn = 1;
41534b92 2367 }
af9c9be3
BA
2368 else if (!move.next)
2369 this.subTurn++;
5f08c59b
BA
2370 }
2371
2372 isLastMove(move) {
af9c9be3
BA
2373 if (move.next)
2374 return false;
2375 const color = this.turn;
6b9320bb 2376 const oppKingPos = this.searchKingPos(C.GetOppCol(color));
a548cb4e 2377 if (oppKingPos.length == 0 || this.underCheck(oppKingPos, color))
af9c9be3 2378 return true;
5f08c59b 2379 return (
af9c9be3
BA
2380 (
2381 !this.options["balance"] ||
6b9320bb
BA
2382 ![1, 2].includes(this.movesCount) ||
2383 this.subTurn == 2
af9c9be3
BA
2384 )
2385 &&
2386 (
2387 !this.options["doublemove"] ||
2388 this.movesCount == 0 ||
2389 this.subTurn == 2
2390 )
2391 &&
2392 (
2393 !this.options["progressive"] ||
2394 this.subTurn == this.movesCount + 1
2395 )
5f08c59b 2396 );
41534b92
BA
2397 }
2398
2399 // "Stop at the first move found"
2400 atLeastOneMove(color) {
41534b92
BA
2401 for (let i = 0; i < this.size.x; i++) {
2402 for (let j = 0; j < this.size.y; j++) {
2403 if (this.board[i][j] != "" && this.getColor(i, j) == color) {
cc2c7183
BA
2404 // NOTE: in fact searching for all potential moves from i,j.
2405 // I don't believe this is an issue, for now at least.
41534b92 2406 const moves = this.getPotentialMovesFrom([i, j]);
b4ae3ff6
BA
2407 if (moves.some(m => this.filterValid([m]).length >= 1))
2408 return true;
41534b92
BA
2409 }
2410 }
2411 }
2412 if (this.hasReserve && this.reserve[color]) {
2413 for (let p of Object.keys(this.reserve[color])) {
2414 const moves = this.getDropMovesFrom([color, p]);
b4ae3ff6
BA
2415 if (moves.some(m => this.filterValid([m]).length >= 1))
2416 return true;
41534b92
BA
2417 }
2418 }
2419 return false;
2420 }
2421
2422 // What is the score ? (Interesting if game is over)
d6d0a46e
BA
2423 getCurrentScore(move_s) {
2424 const move = move_s[move_s.length - 1];
2425 // Shortcut in case the score was computed before:
2426 if (move.result)
2427 return move.result;
41534b92 2428 const color = this.turn;
cc2c7183 2429 const oppCol = C.GetOppCol(color);
a548cb4e
BA
2430 const kingPos = {
2431 [color]: this.searchKingPos(color),
2432 [oppCol]: this.searchKingPos(oppCol)
2433 };
2434 if (kingPos[color].length == 0 && kingPos[oppCol].length == 0)
b4ae3ff6 2435 return "1/2";
a548cb4e 2436 if (kingPos[color].length == 0)
b4ae3ff6 2437 return (color == "w" ? "0-1" : "1-0");
a548cb4e 2438 if (kingPos[oppCol].length == 0)
b4ae3ff6 2439 return (color == "w" ? "1-0" : "0-1");
6b9320bb 2440 if (this.atLeastOneMove(color))
b4ae3ff6 2441 return "*";
41534b92 2442 // No valid move: stalemate or checkmate?
a548cb4e 2443 if (!this.underCheck(kingPos[color], oppCol))
b4ae3ff6 2444 return "1/2";
41534b92
BA
2445 // OK, checkmate
2446 return (color == "w" ? "0-1" : "1-0");
2447 }
2448
41534b92
BA
2449 playVisual(move, r) {
2450 move.vanish.forEach(v => {
f77da909 2451 this.g_pieces[v.x][v.y].remove();
c9ab0340 2452 this.g_pieces[v.x][v.y] = null;
41534b92 2453 });
3c61449b
BA
2454 let chessboard =
2455 document.getElementById(this.containerId).querySelector(".chessboard");
b4ae3ff6
BA
2456 if (!r)
2457 r = chessboard.getBoundingClientRect();
41534b92
BA
2458 const pieceWidth = this.getPieceWidth(r.width);
2459 move.appear.forEach(a => {
41534b92 2460 this.g_pieces[a.x][a.y] = document.createElement("piece");
2159c239
BA
2461 C.AddClass_es(this.g_pieces[a.x][a.y],
2462 this.pieces(a.c, a.x, a.y)[a.p]["class"]);
bc2bc396 2463 this.g_pieces[a.x][a.y].classList.add(C.GetColorClass(a.c));
41534b92
BA
2464 this.g_pieces[a.x][a.y].style.width = pieceWidth + "px";
2465 this.g_pieces[a.x][a.y].style.height = pieceWidth + "px";
2466 const [ip, jp] = this.getPixelPosition(a.x, a.y, r);
9db5050a
BA
2467 // Translate coordinates to use chessboard as reference:
2468 this.g_pieces[a.x][a.y].style.transform =
2469 `translate(${ip - r.x}px,${jp - r.y}px)`;
c9ab0340
BA
2470 if (this.enlightened && !this.enlightened[a.x][a.y])
2471 this.g_pieces[a.x][a.y].classList.add("hidden");
3c61449b 2472 chessboard.appendChild(this.g_pieces[a.x][a.y]);
41534b92 2473 });
c9ab0340
BA
2474 if (this.options["dark"])
2475 this.graphUpdateEnlightened();
41534b92
BA
2476 }
2477
5f08c59b 2478 // TODO: send stack receive stack, or allow incremental? (good/bad points)
e7d409fc 2479 buildMoveStack(move, r) {
5f08c59b
BA
2480 this.moveStack.push(move);
2481 this.computeNextMove(move);
41534b92 2482 this.play(move);
5f08c59b 2483 const newTurn = this.turn;
98d14451 2484 if (this.moveStack.length == 1 && !this.hideMoves)
e7d409fc
BA
2485 this.playVisual(move, r);
2486 if (move.next) {
5f08c59b
BA
2487 this.gameState = {
2488 fen: this.getFen(),
2489 board: JSON.parse(JSON.stringify(this.board)) //easier
2490 };
e7d409fc 2491 this.buildMoveStack(move.next, r);
5f08c59b 2492 }
5f08c59b 2493 else {
5f08c59b 2494 if (this.moveStack.length == 1) {
e7d409fc 2495 // Usual case (one normal move)
5f08c59b
BA
2496 this.afterPlay(this.moveStack, newTurn, {send: true, res: true});
2497 this.moveStack = []
2498 }
2499 else {
2500 this.afterPlay(this.moveStack, newTurn, {send: true, res: false});
2501 this.re_initFromFen(this.gameState.fen, this.gameState.board);
2502 this.playReceivedMove(this.moveStack.slice(1), () => {
2503 this.afterPlay(this.moveStack, newTurn, {send: false, res: true});
2504 this.moveStack = []
2505 });
2506 }
2507 }
41534b92
BA
2508 }
2509
5f08c59b
BA
2510 // Implemented in variants using (automatic) moveStack
2511 computeNextMove(move) {}
2512
5f08c59b
BA
2513 animateMoving(start, end, drag, segments, cb) {
2514 let initPiece = this.getDomPiece(start.x, start.y);
2515 // NOTE: cloning often not required, but light enough, and simpler
9db5050a
BA
2516 let movingPiece = initPiece.cloneNode();
2517 initPiece.style.opacity = "0";
2518 let container =
2519 document.getElementById(this.containerId)
2520 const r = container.querySelector(".chessboard").getBoundingClientRect();
5f08c59b 2521 if (typeof start.x == "string") {
082e639a
BA
2522 // Need to bound width/height (was 100% for reserve pieces)
2523 const pieceWidth = this.getPieceWidth(r.width);
2524 movingPiece.style.width = pieceWidth + "px";
2525 movingPiece.style.height = pieceWidth + "px";
2526 }
f55a0a67 2527 const maxDist = this.getMaxDistance(r);
5f08c59b
BA
2528 const apparentColor = this.getColor(start.x, start.y);
2529 const pieces = this.pieces(apparentColor, start.x, start.y);
2530 if (drag) {
2531 const startCode = this.getPiece(start.x, start.y);
3b641716 2532 C.RemoveClass_es(movingPiece, pieces[startCode]["class"]);
5f08c59b
BA
2533 C.AddClass_es(movingPiece, pieces[drag.p]["class"]);
2534 if (apparentColor != drag.c) {
15106e82 2535 movingPiece.classList.remove(C.GetColorClass(apparentColor));
5f08c59b 2536 movingPiece.classList.add(C.GetColorClass(drag.c));
41534b92 2537 }
41534b92 2538 }
9db5050a 2539 container.appendChild(movingPiece);
15106e82 2540 const animateSegment = (index, cb) => {
9db5050a 2541 // NOTE: move.drag could be generalized per-segment (usage?)
5f08c59b
BA
2542 const [i1, j1] = segments[index][0];
2543 const [i2, j2] = segments[index][1];
15106e82
BA
2544 const dep = this.getPixelPosition(i1, j1, r);
2545 const arr = this.getPixelPosition(i2, j2, r);
9db5050a
BA
2546 movingPiece.style.transitionDuration = "0s";
2547 movingPiece.style.transform = `translate(${dep[0]}px, ${dep[1]}px)`;
15106e82
BA
2548 const distance =
2549 Math.sqrt((arr[0] - dep[0]) ** 2 + (arr[1] - dep[1]) ** 2);
2550 const duration = 0.2 + (distance / maxDist) * 0.3;
9db5050a
BA
2551 // TODO: unclear why we need this new delay below:
2552 setTimeout(() => {
2553 movingPiece.style.transitionDuration = duration + "s";
adf7c659 2554 // movingPiece is child of container: no need to adjust coordinates
9db5050a
BA
2555 movingPiece.style.transform = `translate(${arr[0]}px, ${arr[1]}px)`;
2556 setTimeout(cb, duration * 1000);
2557 }, 50);
15106e82 2558 };
15106e82 2559 let index = 0;
635418a5 2560 const animateSegmentCallback = () => {
5f08c59b 2561 if (index < segments.length)
635418a5 2562 animateSegment(index++, animateSegmentCallback);
15106e82 2563 else {
9db5050a
BA
2564 movingPiece.remove();
2565 initPiece.style.opacity = "1";
5f08c59b 2566 cb();
15106e82 2567 }
635418a5
BA
2568 };
2569 animateSegmentCallback();
41534b92
BA
2570 }
2571
5f08c59b
BA
2572 // Input array of objects with at least fields x,y (e.g. PiPo)
2573 animateFading(arr, cb) {
2574 const animLength = 350; //TODO: 350ms? More? Less?
2575 arr.forEach(v => {
2576 let fadingPiece = this.getDomPiece(v.x, v.y);
2577 fadingPiece.style.transitionDuration = (animLength / 1000) + "s";
2578 fadingPiece.style.opacity = "0";
2579 });
2580 setTimeout(cb, animLength);
2581 }
2582
2583 animate(move, callback) {
2584 if (this.noAnimate || move.noAnimate) {
2585 callback();
2586 return;
2587 }
2588 let segments = move.segments;
2589 if (!segments)
2590 segments = [ [[move.start.x, move.start.y], [move.end.x, move.end.y]] ];
2591 let targetObj = new TargetObj(callback);
2592 if (move.start.x != move.end.x || move.start.y != move.end.y) {
2593 targetObj.target++;
2594 this.animateMoving(move.start, move.end, move.drag, segments,
2595 () => targetObj.increment());
2596 }
2597 if (move.vanish.length > move.appear.length) {
2598 const arr = move.vanish.slice(move.appear.length)
e7d409fc
BA
2599 // Ignore disappearing pieces hidden by some appearing ones:
2600 .filter(v => move.appear.every(a => a.x != v.x || a.y != v.y));
5f08c59b
BA
2601 if (arr.length > 0) {
2602 targetObj.target++;
2603 this.animateFading(arr, () => targetObj.increment());
2604 }
2605 }
462947f0
BA
2606 targetObj.target +=
2607 this.tryAnimateCastle(move, () => targetObj.increment());
5f08c59b
BA
2608 targetObj.target +=
2609 this.customAnimate(move, segments, () => targetObj.increment());
2610 if (targetObj.target == 0)
2611 callback();
2612 }
2613
462947f0
BA
2614 tryAnimateCastle(move, cb) {
2615 if (
2616 this.hasCastle &&
2617 move.vanish.length == 2 &&
2618 move.appear.length == 2 &&
2619 this.isKing(0, 0, move.vanish[0].p) &&
2620 this.isKing(0, 0, move.appear[0].p)
2621 ) {
2622 const start = {x: move.vanish[1].x, y: move.vanish[1].y},
2623 end = {x: move.appear[1].x, y: move.appear[1].y};
2624 const segments = [ [[start.x, start.y], [end.x, end.y]] ];
2625 this.animateMoving(start, end, null, segments, cb);
2626 return 1;
2627 }
2628 return 0;
2629 }
2630
5f08c59b
BA
2631 // Potential other animations (e.g. for Suction variant)
2632 customAnimate(move, segments, cb) {
2633 return 0; //nb of targets
2634 }
2635
126ffc70 2636 launchAnimation(moves, container, callback) {
98d14451
BA
2637 if (this.hideMoves) {
2638 moves.forEach(m => this.play(m));
2639 callback();
2640 return;
2641 }
2642 const r = container.querySelector(".chessboard").getBoundingClientRect();
2643 const animateRec = i => {
2644 this.animate(moves[i], () => {
2645 this.play(moves[i]);
2646 this.playVisual(moves[i], r);
2647 if (i < moves.length - 1)
2648 setTimeout(() => animateRec(i+1), 300);
2649 else
2650 callback();
2651 });
21e8e712 2652 };
98d14451
BA
2653 animateRec(0);
2654 }
2655
2656 playReceivedMove(moves, callback) {
e081c5eb
BA
2657 // Delay if user wasn't focused:
2658 const checkDisplayThenAnimate = (delay) => {
3c61449b 2659 if (container.style.display == "none") {
21e8e712
BA
2660 alert("New move! Let's go back to game...");
2661 document.getElementById("gameInfos").style.display = "none";
3c61449b 2662 container.style.display = "block";
126ffc70
BA
2663 setTimeout(
2664 () => this.launchAnimation(moves, container, callback),
2665 700
2666 );
2667 }
2668 else {
2669 setTimeout(
2670 () => this.launchAnimation(moves, container, callback),
2671 delay || 0
2672 );
21e8e712 2673 }
21e8e712 2674 };
3c61449b 2675 let container = document.getElementById(this.containerId);
016306e3
BA
2676 if (document.hidden) {
2677 document.onvisibilitychange = () => {
2678 document.onvisibilitychange = undefined;
e081c5eb 2679 checkDisplayThenAnimate(700);
fd31883b 2680 };
fd31883b 2681 }
b4ae3ff6
BA
2682 else
2683 checkDisplayThenAnimate();
41534b92
BA
2684 }
2685
2686};