More efficient Synchrone chess + fix a bug. FIrst draft of Apocalypse
[vchess.git] / client / src / components / Board.vue
CommitLineData
24340cae 1<script>
e2732923
BA
2import { getSquareId, getSquareFromId } from "@/utils/squareId";
3import { ArrayFun } from "@/utils/array";
dfeb96ea 4import { store } from "@/store";
cf2343ce 5export default {
6808d7a1 6 name: "my-board",
cf2343ce
BA
7 // Last move cannot be guessed from here, and is required to highlight squares
8 // vr: object to check moves, print board...
93d1d7a7 9 // userColor is left undefined for an external observer
6808d7a1
BA
10 props: [
11 "vr",
12 "lastMove",
13 "analyze",
20620465 14 "score",
6808d7a1
BA
15 "incheck",
16 "orientation",
17 "userColor",
18 "vname"
19 ],
20 data: function() {
cf2343ce 21 return {
cafe0166 22 mobileBrowser: ("ontouchstart" in window),
cf2343ce
BA
23 possibleMoves: [], //filled after each valid click/dragstart
24 choices: [], //promotion pieces, or checkered captures... (as moves)
25 selectedPiece: null, //moving piece (or clicked piece)
28b32b4f
BA
26 start: null, //pixels coordinates + id of starting square (click or drag)
27 click: "",
3a2a7b5f 28 clickTime: 0,
6808d7a1 29 settings: store.state.settings
cf2343ce
BA
30 };
31 },
32 render(h) {
6808d7a1 33 if (!this.vr) {
7b3cf1b7 34 // Return empty div of class 'game' to avoid error when setting size
6808d7a1
BA
35 return h("div", {
36 class: {
37 game: true
38 }
39 });
7b3cf1b7 40 }
6808d7a1 41 const [sizeX, sizeY] = [V.size.x, V.size.y];
cf2343ce 42 // Precompute hints squares to facilitate rendering
e2732923 43 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
6808d7a1
BA
44 this.possibleMoves.forEach(m => {
45 hintSquares[m.end.x][m.end.y] = true;
46 });
cf2343ce 47 // Also precompute in-check squares
e2732923 48 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
6808d7a1
BA
49 this.incheck.forEach(sq => {
50 incheckSq[sq[0]][sq[1]] = true;
51 });
06e79b07 52
cf2343ce 53 const lm = this.lastMove;
57eb158f
BA
54 const showLight = (
55 this.settings.highlight &&
56 ["all","highlight"].includes(V.ShowMoves)
57 );
d54f6261
BA
58 const showCheck = (
59 this.settings.highlight &&
60 ["all","highlight","byrow"].includes(V.ShowMoves)
61 );
311cba76
BA
62 const orientation = !V.CanFlip ? "w" : this.orientation;
63 // Ensure that squares colors do not change when board is flipped
64 const lightSquareMod = (sizeX + sizeY) % 2;
65 const showPiece = (x, y) => {
66 return (
67 this.vr.board[x][y] != V.EMPTY &&
68 (!this.vr.enlightened || this.analyze || this.score != "*" ||
69 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
70 );
71 };
72 const inHighlight = (x, y) => {
73 return showLight && !!lm && (
74 (lm.end.x == x && lm.end.y == y) ||
75 (lm.start.x == x && lm.start.y == y));
76 };
77 const inShadow = (x, y) => {
78 return (
79 !this.analyze &&
80 this.score == "*" &&
81 this.vr.enlightened &&
82 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
83 );
84 };
85 // Create board element (+ reserves if needed by variant)
9d4a0218 86 let elementArray = [];
cf2343ce 87 const gameDiv = h(
6808d7a1 88 "div",
cf2343ce 89 {
6808d7a1
BA
90 class: {
91 game: true,
92 clearer: true
93 }
cf2343ce
BA
94 },
95 [...Array(sizeX).keys()].map(i => {
311cba76 96 const ci = orientation == "w" ? i : sizeX - i - 1;
cf2343ce 97 return h(
6808d7a1 98 "div",
cf2343ce 99 {
6808d7a1
BA
100 class: {
101 row: true
cf2343ce 102 },
6808d7a1 103 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
cf2343ce
BA
104 },
105 [...Array(sizeY).keys()].map(j => {
311cba76 106 const cj = orientation == "w" ? j : sizeY - j - 1;
cf2343ce 107 let elems = [];
311cba76 108 if (showPiece(ci, cj)) {
cf2343ce 109 elems.push(
6808d7a1
BA
110 h("img", {
111 class: {
112 piece: true,
113 ghost:
114 !!this.selectedPiece &&
115 this.selectedPiece.parentNode.id == "sq-" + ci + "-" + cj
116 },
117 attrs: {
118 src:
119 "/images/pieces/" +
3a2a7b5f
BA
120 this.vr.getPpath(
121 this.vr.board[ci][cj],
122 // Extra args useful for some variants:
123 this.userColor,
124 this.score,
125 this.orientation) +
14edde72 126 V.IMAGE_EXTENSION
cf2343ce 127 }
6808d7a1 128 })
cf2343ce
BA
129 );
130 }
6808d7a1 131 if (this.settings.hints && hintSquares[ci][cj]) {
cf2343ce 132 elems.push(
6808d7a1
BA
133 h("img", {
134 class: {
135 "mark-square": true
136 },
137 attrs: {
138 src: "/images/mark.svg"
cf2343ce 139 }
6808d7a1 140 })
cf2343ce
BA
141 );
142 }
311cba76 143 const lightSquare = (ci + cj) % 2 == lightSquareMod;
cf2343ce 144 return h(
6808d7a1 145 "div",
cf2343ce 146 {
6808d7a1
BA
147 class: {
148 board: true,
149 ["board" + sizeY]: true,
311cba76
BA
150 "light-square": lightSquare,
151 "dark-square": !lightSquare,
dfeb96ea 152 [this.settings.bcolor]: true,
311cba76
BA
153 "in-shadow": inShadow(ci, cj),
154 "highlight-light": inHighlight(ci, cj) && lightSquare,
155 "highlight-dark": inHighlight(ci, cj) && !lightSquare,
d54f6261
BA
156 "incheck-light": showCheck && lightSquare && incheckSq[ci][cj],
157 "incheck-dark": showCheck && !lightSquare && incheckSq[ci][cj]
cf2343ce
BA
158 },
159 attrs: {
6808d7a1
BA
160 id: getSquareId({ x: ci, y: cj })
161 }
cf2343ce
BA
162 },
163 elems
164 );
165 })
166 );
24340cae 167 })
cf2343ce 168 );
9d4a0218
BA
169 if (!!this.vr.reserve) {
170 const playingColor = this.userColor || "w"; //default for an observer
6808d7a1 171 const shiftIdx = playingColor == "w" ? 0 : 1;
cf2343ce 172 let myReservePiecesArray = [];
6808d7a1 173 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
9d4a0218 174 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
6808d7a1
BA
175 myReservePiecesArray.push(
176 h(
177 "div",
178 {
179 class: { board: true, ["board" + sizeY]: true },
9d4a0218
BA
180 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
181 style: { opacity: qty > 0 ? 1 : 0.35 }
6808d7a1
BA
182 },
183 [
184 h("img", {
185 class: { piece: true, reserve: true },
186 attrs: {
187 src:
188 "/images/pieces/" +
241bf8f2 189 this.vr.getReservePpath(i, playingColor) +
6808d7a1
BA
190 ".svg"
191 }
192 }),
9d4a0218 193 h("sup", { class: { "reserve-count": true } }, [ qty ])
6808d7a1 194 ]
cf2343ce 195 )
6808d7a1 196 );
cf2343ce
BA
197 }
198 let oppReservePiecesArray = [];
93d1d7a7 199 const oppCol = V.GetOppCol(playingColor);
6808d7a1 200 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
9d4a0218 201 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
6808d7a1
BA
202 oppReservePiecesArray.push(
203 h(
204 "div",
205 {
206 class: { board: true, ["board" + sizeY]: true },
9d4a0218
BA
207 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
208 style: { opacity: qty > 0 ? 1 : 0.35 }
6808d7a1
BA
209 },
210 [
211 h("img", {
212 class: { piece: true, reserve: true },
213 attrs: {
214 src:
215 "/images/pieces/" +
241bf8f2 216 this.vr.getReservePpath(i, oppCol) +
6808d7a1
BA
217 ".svg"
218 }
219 }),
9d4a0218 220 h("sup", { class: { "reserve-count": true } }, [ qty ])
6808d7a1 221 ]
cf2343ce 222 )
6808d7a1 223 );
cf2343ce 224 }
9d4a0218
BA
225 const myReserveTop = (
226 (playingColor == 'w' && orientation == 'b') ||
227 (playingColor == 'b' && orientation == 'w')
cf2343ce 228 );
9d4a0218
BA
229 // Center reserves, assuming same number of pieces for each side:
230 const nbReservePieces = myReservePiecesArray.length;
231 const marginLeft = ((100 - nbReservePieces * (100 / sizeY)) / 2) + "%";
232 const reserveTop =
233 h(
234 "div",
235 {
236 class: {
237 game: true,
238 "reserve-div": true
239 },
240 style: {
241 "margin-left": marginLeft
242 }
243 },
244 [
245 h(
246 "div",
247 {
248 class: {
249 row: true,
250 "reserve-row": true
251 }
252 },
253 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
254 )
255 ]
256 );
257 var reserveBottom =
258 h(
259 "div",
260 {
261 class: {
262 game: true,
263 "reserve-div": true
264 },
265 style: {
266 "margin-left": marginLeft
267 }
268 },
269 [
270 h(
271 "div",
272 {
273 class: {
274 row: true,
275 "reserve-row": true
276 }
277 },
278 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
279 )
280 ]
281 );
282 elementArray.push(reserveTop);
cf2343ce 283 }
9d4a0218
BA
284 elementArray.push(gameDiv);
285 if (!!this.vr.reserve) elementArray.push(reserveBottom);
aafe9f16 286 const boardElt = document.querySelector(".game");
6808d7a1 287 if (this.choices.length > 0 && !!boardElt) {
afbf3ca7 288 // No choices to show at first drawing
aafe9f16
BA
289 const squareWidth = boardElt.offsetWidth / sizeY;
290 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
14edde72
BA
291 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
292 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
293 let choicesHeight = squareWidth;
294 if (this.choices.length >= sizeY) {
295 // A second row is required (Eightpieces variant)
296 topOffset -= squareWidth / 2;
297 choicesHeight *= 2;
298 }
aafe9f16 299 const choices = h(
6808d7a1 300 "div",
aafe9f16 301 {
6808d7a1
BA
302 attrs: { id: "choices" },
303 class: { row: true },
aafe9f16 304 style: {
14edde72 305 top: topOffset + "px",
6808d7a1
BA
306 left:
307 offset[1] +
14edde72 308 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
6808d7a1 309 "px",
14edde72
BA
310 width: (maxNbeltsPerRow * squareWidth) + "px",
311 height: choicesHeight + "px"
6808d7a1 312 }
aafe9f16 313 },
14edde72
BA
314 [ h(
315 "div",
316 { },
317 this.choices.map(m => {
318 // A "choice" is a move
319 const applyMove = (e) => {
320 e.stopPropagation();
321 // Force a delay between move is shown and clicked
322 // (otherwise a "double-click" bug might occur)
323 if (Date.now() - this.clickTime < 200) return;
14edde72 324 this.choices = [];
78c23cd6 325 this.play(m);
14edde72
BA
326 };
327 const onClick =
328 this.mobileBrowser
329 ? { touchend: applyMove }
330 : { mouseup: applyMove };
331 return h(
332 "div",
333 {
334 class: {
335 board: true,
336 ["board" + sizeY]: true
aafe9f16 337 },
14edde72
BA
338 style: {
339 width: (100 / maxNbeltsPerRow) + "%",
340 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
341 }
342 },
343 [
344 h("img", {
345 attrs: {
346 src:
347 "/images/pieces/" +
c7550017
BA
348 // orientation: extra arg useful for some variants:
349 this.vr.getPPpath(m, this.orientation) +
14edde72
BA
350 V.IMAGE_EXTENSION
351 },
352 class: { "choice-piece": true },
353 on: onClick
354 })
355 ]
356 );
357 })
358 ) ]
aafe9f16
BA
359 );
360 elementArray.unshift(choices);
361 }
4b26ecb8
BA
362 let onEvents = {};
363 // NOTE: click = mousedown + mouseup
cafe0166 364 if (this.mobileBrowser) {
4b26ecb8
BA
365 onEvents = {
366 on: {
367 touchstart: this.mousedown,
368 touchmove: this.mousemove,
6808d7a1
BA
369 touchend: this.mouseup
370 }
4b26ecb8 371 };
6808d7a1 372 } else {
4b26ecb8 373 onEvents = {
cf2343ce 374 on: {
65495c17
BA
375 mousedown: this.mousedown,
376 mousemove: this.mousemove,
6808d7a1
BA
377 mouseup: this.mouseup
378 }
4b26ecb8
BA
379 };
380 }
6808d7a1 381 return h("div", onEvents, elementArray);
cf2343ce
BA
382 },
383 methods: {
384 mousedown: function(e) {
28b32b4f
BA
385 e.preventDefault();
386 if (!this.start) {
387 // Start square must contain a piece.
388 // NOTE: classList[0] is enough: 'piece' is the first assigned class
389 if (e.target.classList[0] != "piece") return;
390 let parent = e.target.parentNode; //surrounding square
391 // Show possible moves if current player allowed to play
392 const startSquare = getSquareFromId(parent.id);
393 this.possibleMoves = [];
394 const color = this.analyze ? this.vr.turn : this.userColor;
395 if (this.vr.canIplay(color, startSquare))
396 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
397 // For potential drag'n drop, remember start coordinates
398 // (to center the piece on mouse cursor)
399 let rect = parent.getBoundingClientRect();
400 this.start = {
401 x: rect.x + rect.width / 2,
402 y: rect.y + rect.width / 2,
403 id: parent.id
404 };
405 // Add the moving piece to the board, just after current image
406 this.selectedPiece = e.target.cloneNode();
407 Object.assign(
408 this.selectedPiece.style,
409 {
410 position: "absolute",
411 top: 0,
412 display: "inline-block",
413 zIndex: 3000
414 }
415 );
416 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
417 } else {
418 this.processMoveAttempt(e);
419 }
cf2343ce
BA
420 },
421 mousemove: function(e) {
6808d7a1 422 if (!this.selectedPiece) return;
28b32b4f 423 e.preventDefault();
aafe9f16 424 // There is an active element: move it around
cafe0166
BA
425 const [offsetX, offsetY] =
426 this.mobileBrowser
427 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
428 : [e.clientX, e.clientY];
28b32b4f
BA
429 Object.assign(
430 this.selectedPiece.style,
431 {
432 left: offsetX - this.start.x + "px",
433 top: offsetY - this.start.y + "px"
434 }
435 );
cf2343ce
BA
436 },
437 mouseup: function(e) {
6808d7a1 438 if (!this.selectedPiece) return;
28b32b4f
BA
439 e.preventDefault();
440 // Drag'n drop. Selected piece is no longer needed:
441 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
442 delete this.selectedPiece;
443 this.selectedPiece = null;
444 this.processMoveAttempt(e);
445 },
446 processMoveAttempt: function(e) {
447 // Obtain the move from start and end squares
cafe0166
BA
448 const [offsetX, offsetY] =
449 this.mobileBrowser
450 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
451 : [e.clientX, e.clientY];
cf2343ce 452 let landing = document.elementFromPoint(offsetX, offsetY);
cf2343ce 453 // Next condition: classList.contains(piece) fails because of marks
6808d7a1 454 while (landing.tagName == "IMG") landing = landing.parentNode;
28b32b4f
BA
455 if (this.start.id == landing.id) {
456 if (this.click == landing.id) {
457 // Second click on same square: cancel current move
458 this.possibleMoves = [];
459 this.start = null;
460 this.click = "";
461 } else this.click = landing.id;
cf2343ce 462 return;
28b32b4f
BA
463 }
464 this.start = null;
bd76b456 465 // OK: process move attempt, landing is a square node
cf2343ce
BA
466 let endSquare = getSquareFromId(landing.id);
467 let moves = this.findMatchingMoves(endSquare);
468 this.possibleMoves = [];
3a2a7b5f
BA
469 if (moves.length > 1) {
470 this.clickTime = Date.now();
471 this.choices = moves;
472 } else if (moves.length == 1) this.play(moves[0]);
28b32b4f 473 // else: forbidden move attempt
cf2343ce
BA
474 },
475 findMatchingMoves: function(endSquare) {
476 // Run through moves list and return the matching set (if promotions...)
28b32b4f
BA
477 return (
478 this.possibleMoves.filter(m => {
479 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
480 })
481 );
cf2343ce
BA
482 },
483 play: function(move) {
6808d7a1
BA
484 this.$emit("play-move", move);
485 }
486 }
cf2343ce
BA
487};
488</script>
4473050c 489
41c80bb6 490<style lang="sass" scoped>
50aed5a1
BA
491.game.reserve-div
492 margin-bottom: 18px
493
494.reserve-count
495 padding-left: 40%
496
9d4a0218 497.reserve-row
50aed5a1
BA
498 margin-bottom: 15px
499
41cb9b94
BA
500// NOTE: no variants with reserve of size != 8
501
50aed5a1 502.game
28b32b4f 503 user-select: none
cf94b843
BA
504 width: 100%
505 margin: 0
50aed5a1
BA
506 .board
507 cursor: pointer
50aed5a1
BA
508
509#choices
28b32b4f 510 user-select: none
168a5e4c
BA
511 margin: 0
512 position: absolute
50aed5a1
BA
513 z-index: 300
514 overflow-y: inherit
515 background-color: rgba(0,0,0,0)
516 img
517 cursor: pointer
518 background-color: #e6ee9c
519 &:hover
520 background-color: skyblue
521 &.choice-piece
522 width: 100%
523 height: auto
524 display: block
525
50aed5a1
BA
526img.ghost
527 position: absolute
28b32b4f 528 opacity: 0.5
50aed5a1
BA
529 top: 0
530
311cba76
BA
531.incheck-light
532 background-color: rgba(204, 51, 0, 0.7) !important
533.incheck-dark
534 background-color: rgba(204, 51, 0, 0.9) !important
50aed5a1
BA
535
536.light-square.lichess
537 background-color: #f0d9b5;
538.dark-square.lichess
539 background-color: #b58863;
540
541.light-square.chesscom
542 background-color: #e5e5ca;
543.dark-square.chesscom
544 background-color: #6f8f57;
545
546.light-square.chesstempo
28b32b4f 547 background-color: #dfdfdf;
50aed5a1 548.dark-square.chesstempo
28b32b4f
BA
549 background-color: #7287b6;
550
551// TODO: no predefined highlight colors, but layers. How?
552
553.light-square.lichess.highlight-light
b0a0468a 554 background-color: #cdd26a
28b32b4f 555.dark-square.lichess.highlight-dark
b0a0468a 556 background-color: #aaa23a
28b32b4f
BA
557
558.light-square.chesscom.highlight-light
b0a0468a 559 background-color: #f7f783
28b32b4f 560.dark-square.chesscom.highlight-dark
b0a0468a 561 background-color: #bacb44
28b32b4f
BA
562
563.light-square.chesstempo.highlight-light
b0a0468a 564 background-color: #9f9fff
28b32b4f 565.dark-square.chesstempo.highlight-dark
b0a0468a 566 background-color: #557fff
28b32b4f 567
4473050c 568</style>