Add unambiguous section in the PGN + some fixes + code formatting and fix typos
[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",
2c5d7b20 7 // Last move cannot be guessed from here, and is required for highlights.
cf2343ce 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 {
6ec2feb2 90 "class": {
6808d7a1
BA
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 {
6ec2feb2 100 "class": {
6808d7a1 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 110 h("img", {
6ec2feb2 111 "class": {
6808d7a1
BA
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 133 h("img", {
6ec2feb2 134 "class": {
6808d7a1
BA
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 {
6ec2feb2 147 "class": {
6808d7a1
BA
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,
2c5d7b20
BA
156 "incheck-light":
157 showCheck && lightSquare && incheckSq[ci][cj],
158 "incheck-dark":
159 showCheck && !lightSquare && incheckSq[ci][cj]
cf2343ce
BA
160 },
161 attrs: {
6808d7a1
BA
162 id: getSquareId({ x: ci, y: cj })
163 }
cf2343ce
BA
164 },
165 elems
166 );
167 })
168 );
24340cae 169 })
cf2343ce 170 );
9d4a0218
BA
171 if (!!this.vr.reserve) {
172 const playingColor = this.userColor || "w"; //default for an observer
6808d7a1 173 const shiftIdx = playingColor == "w" ? 0 : 1;
cf2343ce 174 let myReservePiecesArray = [];
6808d7a1 175 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
9d4a0218 176 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
6808d7a1
BA
177 myReservePiecesArray.push(
178 h(
179 "div",
180 {
6ec2feb2 181 "class": { board: true, ["board" + sizeY]: true },
9d4a0218
BA
182 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
183 style: { opacity: qty > 0 ? 1 : 0.35 }
6808d7a1
BA
184 },
185 [
186 h("img", {
6ec2feb2 187 "class": { piece: true, reserve: true },
6808d7a1
BA
188 attrs: {
189 src:
190 "/images/pieces/" +
241bf8f2 191 this.vr.getReservePpath(i, playingColor) +
6808d7a1
BA
192 ".svg"
193 }
194 }),
6ec2feb2 195 h("sup", { "class": { "reserve-count": true } }, [ qty ])
6808d7a1 196 ]
cf2343ce 197 )
6808d7a1 198 );
cf2343ce
BA
199 }
200 let oppReservePiecesArray = [];
93d1d7a7 201 const oppCol = V.GetOppCol(playingColor);
6808d7a1 202 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
9d4a0218 203 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
6808d7a1
BA
204 oppReservePiecesArray.push(
205 h(
206 "div",
207 {
6ec2feb2 208 "class": { board: true, ["board" + sizeY]: true },
9d4a0218
BA
209 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
210 style: { opacity: qty > 0 ? 1 : 0.35 }
6808d7a1
BA
211 },
212 [
213 h("img", {
6ec2feb2 214 "class": { piece: true, reserve: true },
6808d7a1
BA
215 attrs: {
216 src:
217 "/images/pieces/" +
241bf8f2 218 this.vr.getReservePpath(i, oppCol) +
6808d7a1
BA
219 ".svg"
220 }
221 }),
6ec2feb2 222 h("sup", { "class": { "reserve-count": true } }, [ qty ])
6808d7a1 223 ]
cf2343ce 224 )
6808d7a1 225 );
cf2343ce 226 }
9d4a0218
BA
227 const myReserveTop = (
228 (playingColor == 'w' && orientation == 'b') ||
229 (playingColor == 'b' && orientation == 'w')
cf2343ce 230 );
9d4a0218
BA
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 {
6ec2feb2 238 "class": {
9d4a0218
BA
239 game: true,
240 "reserve-div": true
241 },
242 style: {
243 "margin-left": marginLeft
244 }
245 },
246 [
247 h(
248 "div",
249 {
6ec2feb2 250 "class": {
9d4a0218
BA
251 row: true,
252 "reserve-row": true
253 }
254 },
255 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
256 )
257 ]
258 );
259 var reserveBottom =
260 h(
261 "div",
262 {
6ec2feb2 263 "class": {
9d4a0218
BA
264 game: true,
265 "reserve-div": true
266 },
267 style: {
268 "margin-left": marginLeft
269 }
270 },
271 [
272 h(
273 "div",
274 {
6ec2feb2 275 "class": {
9d4a0218
BA
276 row: true,
277 "reserve-row": true
278 }
279 },
280 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
281 )
282 ]
283 );
284 elementArray.push(reserveTop);
cf2343ce 285 }
9d4a0218
BA
286 elementArray.push(gameDiv);
287 if (!!this.vr.reserve) elementArray.push(reserveBottom);
aafe9f16 288 const boardElt = document.querySelector(".game");
6808d7a1 289 if (this.choices.length > 0 && !!boardElt) {
afbf3ca7 290 // No choices to show at first drawing
aafe9f16
BA
291 const squareWidth = boardElt.offsetWidth / sizeY;
292 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
14edde72
BA
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 }
aafe9f16 301 const choices = h(
6808d7a1 302 "div",
aafe9f16 303 {
6808d7a1 304 attrs: { id: "choices" },
6ec2feb2 305 "class": { row: true },
aafe9f16 306 style: {
14edde72 307 top: topOffset + "px",
6808d7a1
BA
308 left:
309 offset[1] +
14edde72 310 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
6808d7a1 311 "px",
14edde72
BA
312 width: (maxNbeltsPerRow * squareWidth) + "px",
313 height: choicesHeight + "px"
6808d7a1 314 }
aafe9f16 315 },
14edde72
BA
316 [ h(
317 "div",
6ec2feb2
BA
318 {
319 "class": { "full-width": true }
320 },
14edde72
BA
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;
14edde72 328 this.choices = [];
78c23cd6 329 this.play(m);
14edde72
BA
330 };
331 const onClick =
332 this.mobileBrowser
333 ? { touchend: applyMove }
334 : { mouseup: applyMove };
335 return h(
336 "div",
337 {
6ec2feb2 338 "class": {
14edde72
BA
339 board: true,
340 ["board" + sizeY]: true
aafe9f16 341 },
14edde72
BA
342 style: {
343 width: (100 / maxNbeltsPerRow) + "%",
344 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
345 }
346 },
347 [
348 h("img", {
349 attrs: {
350 src:
351 "/images/pieces/" +
c7550017
BA
352 // orientation: extra arg useful for some variants:
353 this.vr.getPPpath(m, this.orientation) +
14edde72
BA
354 V.IMAGE_EXTENSION
355 },
6ec2feb2 356 "class": { "choice-piece": true },
14edde72
BA
357 on: onClick
358 })
359 ]
360 );
361 })
362 ) ]
aafe9f16
BA
363 );
364 elementArray.unshift(choices);
365 }
4b26ecb8
BA
366 let onEvents = {};
367 // NOTE: click = mousedown + mouseup
cafe0166 368 if (this.mobileBrowser) {
4b26ecb8
BA
369 onEvents = {
370 on: {
371 touchstart: this.mousedown,
372 touchmove: this.mousemove,
6808d7a1
BA
373 touchend: this.mouseup
374 }
4b26ecb8 375 };
6808d7a1 376 } else {
4b26ecb8 377 onEvents = {
cf2343ce 378 on: {
65495c17
BA
379 mousedown: this.mousedown,
380 mousemove: this.mousemove,
6808d7a1
BA
381 mouseup: this.mouseup
382 }
4b26ecb8
BA
383 };
384 }
6808d7a1 385 return h("div", onEvents, elementArray);
cf2343ce
BA
386 },
387 methods: {
388 mousedown: function(e) {
28b32b4f
BA
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 }
cf2343ce
BA
424 },
425 mousemove: function(e) {
6808d7a1 426 if (!this.selectedPiece) return;
28b32b4f 427 e.preventDefault();
aafe9f16 428 // There is an active element: move it around
cafe0166
BA
429 const [offsetX, offsetY] =
430 this.mobileBrowser
431 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
432 : [e.clientX, e.clientY];
28b32b4f
BA
433 Object.assign(
434 this.selectedPiece.style,
435 {
436 left: offsetX - this.start.x + "px",
437 top: offsetY - this.start.y + "px"
438 }
439 );
cf2343ce
BA
440 },
441 mouseup: function(e) {
6808d7a1 442 if (!this.selectedPiece) return;
28b32b4f
BA
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
cafe0166
BA
452 const [offsetX, offsetY] =
453 this.mobileBrowser
454 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
455 : [e.clientX, e.clientY];
cf2343ce 456 let landing = document.elementFromPoint(offsetX, offsetY);
cf2343ce 457 // Next condition: classList.contains(piece) fails because of marks
6808d7a1 458 while (landing.tagName == "IMG") landing = landing.parentNode;
28b32b4f
BA
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;
cf2343ce 466 return;
28b32b4f
BA
467 }
468 this.start = null;
bd76b456 469 // OK: process move attempt, landing is a square node
cf2343ce
BA
470 let endSquare = getSquareFromId(landing.id);
471 let moves = this.findMatchingMoves(endSquare);
472 this.possibleMoves = [];
3a2a7b5f
BA
473 if (moves.length > 1) {
474 this.clickTime = Date.now();
475 this.choices = moves;
476 } else if (moves.length == 1) this.play(moves[0]);
28b32b4f 477 // else: forbidden move attempt
cf2343ce
BA
478 },
479 findMatchingMoves: function(endSquare) {
480 // Run through moves list and return the matching set (if promotions...)
28b32b4f
BA
481 return (
482 this.possibleMoves.filter(m => {
483 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
484 })
485 );
cf2343ce
BA
486 },
487 play: function(move) {
6808d7a1
BA
488 this.$emit("play-move", move);
489 }
490 }
cf2343ce
BA
491};
492</script>
4473050c 493
41c80bb6 494<style lang="sass" scoped>
6ec2feb2 495// NOTE: no variants with reserve of size != 8
50aed5a1
BA
496.game.reserve-div
497 margin-bottom: 18px
50aed5a1
BA
498.reserve-count
499 padding-left: 40%
9d4a0218 500.reserve-row
50aed5a1
BA
501 margin-bottom: 15px
502
6ec2feb2
BA
503.full-width
504 width: 100%
41cb9b94 505
50aed5a1 506.game
28b32b4f 507 user-select: none
cf94b843
BA
508 width: 100%
509 margin: 0
50aed5a1
BA
510 .board
511 cursor: pointer
50aed5a1
BA
512
513#choices
28b32b4f 514 user-select: none
168a5e4c
BA
515 margin: 0
516 position: absolute
50aed5a1
BA
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
50aed5a1
BA
530img.ghost
531 position: absolute
28b32b4f 532 opacity: 0.5
50aed5a1
BA
533 top: 0
534
311cba76
BA
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
50aed5a1
BA
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
28b32b4f 551 background-color: #dfdfdf;
50aed5a1 552.dark-square.chesstempo
28b32b4f
BA
553 background-color: #7287b6;
554
555// TODO: no predefined highlight colors, but layers. How?
556
557.light-square.lichess.highlight-light
b0a0468a 558 background-color: #cdd26a
28b32b4f 559.dark-square.lichess.highlight-dark
b0a0468a 560 background-color: #aaa23a
28b32b4f
BA
561
562.light-square.chesscom.highlight-light
b0a0468a 563 background-color: #f7f783
28b32b4f 564.dark-square.chesscom.highlight-dark
b0a0468a 565 background-color: #bacb44
28b32b4f
BA
566
567.light-square.chesstempo.highlight-light
b0a0468a 568 background-color: #9f9fff
28b32b4f 569.dark-square.chesstempo.highlight-dark
b0a0468a 570 background-color: #557fff
28b32b4f 571
4473050c 572</style>