Add unambiguous section in the PGN + some fixes + code formatting and fix typos
[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 // Start square must contain a piece.
392 // NOTE: classList[0] is enough: 'piece' is the first assigned class
393 if (e.target.classList[0] != "piece") return;
394 let parent = e.target.parentNode; //surrounding square
395 // Show possible moves if current player allowed to play
396 const startSquare = getSquareFromId(parent.id);
397 this.possibleMoves = [];
398 const color = this.analyze ? this.vr.turn : this.userColor;
399 if (this.vr.canIplay(color, startSquare))
400 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
401 // For potential drag'n drop, remember start coordinates
402 // (to center the piece on mouse cursor)
403 let rect = parent.getBoundingClientRect();
404 this.start = {
405 x: rect.x + rect.width / 2,
406 y: rect.y + rect.width / 2,
407 id: parent.id
408 };
409 // Add the moving piece to the board, just after current image
410 this.selectedPiece = e.target.cloneNode();
411 Object.assign(
412 this.selectedPiece.style,
413 {
414 position: "absolute",
415 top: 0,
416 display: "inline-block",
417 zIndex: 3000
418 }
419 );
420 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
421 } else {
422 this.processMoveAttempt(e);
423 }
424 },
425 mousemove: function(e) {
426 if (!this.selectedPiece) return;
427 e.preventDefault();
428 // There is an active element: move it around
429 const [offsetX, offsetY] =
430 this.mobileBrowser
431 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
432 : [e.clientX, e.clientY];
433 Object.assign(
434 this.selectedPiece.style,
435 {
436 left: offsetX - this.start.x + "px",
437 top: offsetY - this.start.y + "px"
438 }
439 );
440 },
441 mouseup: function(e) {
442 if (!this.selectedPiece) return;
443 e.preventDefault();
444 // Drag'n drop. Selected piece is no longer needed:
445 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
446 delete this.selectedPiece;
447 this.selectedPiece = null;
448 this.processMoveAttempt(e);
449 },
450 processMoveAttempt: function(e) {
451 // Obtain the move from start and end squares
452 const [offsetX, offsetY] =
453 this.mobileBrowser
454 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
455 : [e.clientX, e.clientY];
456 let landing = document.elementFromPoint(offsetX, offsetY);
457 // Next condition: classList.contains(piece) fails because of marks
458 while (landing.tagName == "IMG") landing = landing.parentNode;
459 if (this.start.id == landing.id) {
460 if (this.click == landing.id) {
461 // Second click on same square: cancel current move
462 this.possibleMoves = [];
463 this.start = null;
464 this.click = "";
465 } else this.click = landing.id;
466 return;
467 }
468 this.start = null;
469 // OK: process move attempt, landing is a square node
470 let endSquare = getSquareFromId(landing.id);
471 let moves = this.findMatchingMoves(endSquare);
472 this.possibleMoves = [];
473 if (moves.length > 1) {
474 this.clickTime = Date.now();
475 this.choices = moves;
476 } else if (moves.length == 1) this.play(moves[0]);
477 // else: forbidden move attempt
478 },
479 findMatchingMoves: function(endSquare) {
480 // Run through moves list and return the matching set (if promotions...)
481 return (
482 this.possibleMoves.filter(m => {
483 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
484 })
485 );
486 },
487 play: function(move) {
488 this.$emit("play-move", move);
489 }
490 }
491 };
492 </script>
493
494 <style lang="sass" scoped>
495 // NOTE: no variants with reserve of size != 8
496 .game.reserve-div
497 margin-bottom: 18px
498 .reserve-count
499 padding-left: 40%
500 .reserve-row
501 margin-bottom: 15px
502
503 .full-width
504 width: 100%
505
506 .game
507 user-select: none
508 width: 100%
509 margin: 0
510 .board
511 cursor: pointer
512
513 #choices
514 user-select: none
515 margin: 0
516 position: absolute
517 z-index: 300
518 overflow-y: inherit
519 background-color: rgba(0,0,0,0)
520 img
521 cursor: pointer
522 background-color: #e6ee9c
523 &:hover
524 background-color: skyblue
525 &.choice-piece
526 width: 100%
527 height: auto
528 display: block
529
530 img.ghost
531 position: absolute
532 opacity: 0.5
533 top: 0
534
535 .incheck-light
536 background-color: rgba(204, 51, 0, 0.7) !important
537 .incheck-dark
538 background-color: rgba(204, 51, 0, 0.9) !important
539
540 .light-square.lichess
541 background-color: #f0d9b5;
542 .dark-square.lichess
543 background-color: #b58863;
544
545 .light-square.chesscom
546 background-color: #e5e5ca;
547 .dark-square.chesscom
548 background-color: #6f8f57;
549
550 .light-square.chesstempo
551 background-color: #dfdfdf;
552 .dark-square.chesstempo
553 background-color: #7287b6;
554
555 // TODO: no predefined highlight colors, but layers. How?
556
557 .light-square.lichess.highlight-light
558 background-color: #cdd26a
559 .dark-square.lichess.highlight-dark
560 background-color: #aaa23a
561
562 .light-square.chesscom.highlight-light
563 background-color: #f7f783
564 .dark-square.chesscom.highlight-dark
565 background-color: #bacb44
566
567 .light-square.chesstempo.highlight-light
568 background-color: #9f9fff
569 .dark-square.chesstempo.highlight-dark
570 background-color: #557fff
571
572 </style>