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