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