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