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