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