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