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