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