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