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