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