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