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