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