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