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