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