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