Fix clocks update + abort games from MyGames page
[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 possibleMoves: [], //filled after each valid click/dragstart
23 choices: [], //promotion pieces, or checkered captures... (as moves)
24 selectedPiece: null, //moving piece (or clicked piece)
25 start: {}, //pixels coordinates + id of starting square (click or drag)
26 settings: store.state.settings
27 };
28 },
29 render(h) {
30 if (!this.vr) {
31 // Return empty div of class 'game' to avoid error when setting size
32 return h("div", {
33 class: {
34 game: true
35 }
36 });
37 }
38 const [sizeX, sizeY] = [V.size.x, V.size.y];
39 // Precompute hints squares to facilitate rendering
40 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
41 this.possibleMoves.forEach(m => {
42 hintSquares[m.end.x][m.end.y] = true;
43 });
44 // Also precompute in-check squares
45 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
46 this.incheck.forEach(sq => {
47 incheckSq[sq[0]][sq[1]] = true;
48 });
49
50 const lm = this.lastMove;
51 const showLight = (
52 this.settings.highlight &&
53 ["all","highlight"].includes(V.ShowMoves)
54 );
55 const orientation = !V.CanFlip ? "w" : this.orientation;
56 // Ensure that squares colors do not change when board is flipped
57 const lightSquareMod = (sizeX + sizeY) % 2;
58 const showPiece = (x, y) => {
59 return (
60 this.vr.board[x][y] != V.EMPTY &&
61 (!this.vr.enlightened || this.analyze || this.score != "*" ||
62 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
63 );
64 };
65 const inHighlight = (x, y) => {
66 return showLight && !!lm && (
67 (lm.end.x == x && lm.end.y == y) ||
68 (lm.start.x == x && lm.start.y == y));
69 };
70 const inShadow = (x, y) => {
71 return (
72 !this.analyze &&
73 this.score == "*" &&
74 this.vr.enlightened &&
75 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
76 );
77 };
78 // Create board element (+ reserves if needed by variant)
79 const gameDiv = h(
80 "div",
81 {
82 class: {
83 game: true,
84 clearer: true
85 }
86 },
87 [...Array(sizeX).keys()].map(i => {
88 const ci = orientation == "w" ? i : sizeX - i - 1;
89 return h(
90 "div",
91 {
92 class: {
93 row: true
94 },
95 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
96 },
97 [...Array(sizeY).keys()].map(j => {
98 const cj = orientation == "w" ? j : sizeY - j - 1;
99 let elems = [];
100 if (showPiece(ci, cj)) {
101 elems.push(
102 h("img", {
103 class: {
104 piece: true,
105 ghost:
106 !!this.selectedPiece &&
107 this.selectedPiece.parentNode.id == "sq-" + ci + "-" + cj
108 },
109 attrs: {
110 src:
111 "/images/pieces/" +
112 this.vr.getPpath(this.vr.board[ci][cj], this.userColor, this.score) +
113 ".svg"
114 }
115 })
116 );
117 }
118 if (this.settings.hints && hintSquares[ci][cj]) {
119 elems.push(
120 h("img", {
121 class: {
122 "mark-square": true
123 },
124 attrs: {
125 src: "/images/mark.svg"
126 }
127 })
128 );
129 }
130 const lightSquare = (ci + cj) % 2 == lightSquareMod;
131 return h(
132 "div",
133 {
134 class: {
135 board: true,
136 ["board" + sizeY]: true,
137 "light-square": lightSquare,
138 "dark-square": !lightSquare,
139 [this.settings.bcolor]: true,
140 "in-shadow": inShadow(ci, cj),
141 "highlight-light": inHighlight(ci, cj) && lightSquare,
142 "highlight-dark": inHighlight(ci, cj) && !lightSquare,
143 "incheck-light": showLight && lightSquare && incheckSq[ci][cj],
144 "incheck-dark": showLight && !lightSquare && incheckSq[ci][cj]
145 },
146 attrs: {
147 id: getSquareId({ x: ci, y: cj })
148 }
149 },
150 elems
151 );
152 })
153 );
154 })
155 );
156 let elementArray = [gameDiv];
157 const playingColor = this.userColor || "w"; //default for an observer
158 if (this.vr.reserve) {
159 const shiftIdx = playingColor == "w" ? 0 : 1;
160 let myReservePiecesArray = [];
161 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
162 myReservePiecesArray.push(
163 h(
164 "div",
165 {
166 class: { board: true, ["board" + sizeY]: true },
167 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) }
168 },
169 [
170 h("img", {
171 class: { piece: true, reserve: true },
172 attrs: {
173 src:
174 "/images/pieces/" +
175 this.vr.getReservePpath(i, playingColor) +
176 ".svg"
177 }
178 }),
179 h("sup", { class: { "reserve-count": true } }, [
180 this.vr.reserve[playingColor][V.RESERVE_PIECES[i]]
181 ])
182 ]
183 )
184 );
185 }
186 let oppReservePiecesArray = [];
187 const oppCol = V.GetOppCol(playingColor);
188 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
189 oppReservePiecesArray.push(
190 h(
191 "div",
192 {
193 class: { board: true, ["board" + sizeY]: true },
194 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) }
195 },
196 [
197 h("img", {
198 class: { piece: true, reserve: true },
199 attrs: {
200 src:
201 "/images/pieces/" +
202 this.vr.getReservePpath(i, oppCol) +
203 ".svg"
204 }
205 }),
206 h("sup", { class: { "reserve-count": true } }, [
207 this.vr.reserve[oppCol][V.RESERVE_PIECES[i]]
208 ])
209 ]
210 )
211 );
212 }
213 let reserves = h(
214 "div",
215 {
216 class: {
217 game: true,
218 "reserve-div": true
219 }
220 },
221 [
222 h(
223 "div",
224 {
225 class: {
226 row: true,
227 "reserve-row-1": true
228 }
229 },
230 myReservePiecesArray
231 ),
232 h("div", { class: { row: true } }, oppReservePiecesArray)
233 ]
234 );
235 elementArray.push(reserves);
236 }
237 const boardElt = document.querySelector(".game");
238 if (this.choices.length > 0 && !!boardElt) {
239 //no choices to show at first drawing
240 const squareWidth = boardElt.offsetWidth / sizeY;
241 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
242 const choices = h(
243 "div",
244 {
245 attrs: { id: "choices" },
246 class: { row: true },
247 style: {
248 top: offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2 + "px",
249 left:
250 offset[1] +
251 (squareWidth * (sizeY - this.choices.length)) / 2 +
252 "px",
253 width: this.choices.length * squareWidth + "px",
254 height: squareWidth + "px"
255 }
256 },
257 this.choices.map(m => {
258 //a "choice" is a move
259 return h(
260 "div",
261 {
262 class: {
263 board: true,
264 ["board" + sizeY]: true
265 },
266 style: {
267 width: 100 / this.choices.length + "%",
268 "padding-bottom": 100 / this.choices.length + "%"
269 }
270 },
271 [
272 h("img", {
273 attrs: {
274 src:
275 "/images/pieces/" +
276 this.vr.getPpath(m.appear[0].c + m.appear[0].p) +
277 ".svg"
278 },
279 class: { "choice-piece": true },
280 on: {
281 click: () => {
282 this.play(m);
283 this.choices = [];
284 }
285 }
286 })
287 ]
288 );
289 })
290 );
291 elementArray.unshift(choices);
292 }
293 let onEvents = {};
294 // NOTE: click = mousedown + mouseup
295 if ("ontouchstart" in window) {
296 onEvents = {
297 on: {
298 touchstart: this.mousedown,
299 touchmove: this.mousemove,
300 touchend: this.mouseup
301 }
302 };
303 } else {
304 onEvents = {
305 on: {
306 mousedown: this.mousedown,
307 mousemove: this.mousemove,
308 mouseup: this.mouseup
309 }
310 };
311 }
312 return h("div", onEvents, elementArray);
313 },
314 methods: {
315 mousedown: function(e) {
316 // Abort if a piece is already being processed, or target is not a piece.
317 // NOTE: just looking at classList[0] because piece is the first assigned class
318 if (!!this.selectedPiece || e.target.classList[0] != "piece") return;
319 e.preventDefault(); //disable native drag & drop
320 let parent = e.target.parentNode; //the surrounding square
321 // Next few lines to center the piece on mouse cursor
322 let rect = parent.getBoundingClientRect();
323 this.start = {
324 x: rect.x + rect.width / 2,
325 y: rect.y + rect.width / 2,
326 id: parent.id
327 };
328 this.selectedPiece = e.target.cloneNode();
329 let spStyle = this.selectedPiece.style;
330 spStyle.position = "absolute";
331 spStyle.top = 0;
332 spStyle.display = "inline-block";
333 spStyle.zIndex = 3000;
334 const startSquare = getSquareFromId(parent.id);
335 this.possibleMoves = [];
336 const color = this.analyze ? this.vr.turn : this.userColor;
337 if (this.vr.canIplay(color, startSquare))
338 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
339 // Next line add moving piece just after current image
340 // (required for Crazyhouse reserve)
341 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
342 },
343 mousemove: function(e) {
344 if (!this.selectedPiece) return;
345 // There is an active element: move it around
346 const [offsetX, offsetY] = e.clientX
347 ? [e.clientX, e.clientY] //desktop browser
348 : [e.changedTouches[0].pageX, e.changedTouches[0].pageY]; //smartphone
349 this.selectedPiece.style.left = offsetX - this.start.x + "px";
350 this.selectedPiece.style.top = offsetY - this.start.y + "px";
351 },
352 mouseup: function(e) {
353 if (!this.selectedPiece) return;
354 // There is an active element: obtain the move from start and end squares
355 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coords
356 const [offsetX, offsetY] = e.clientX
357 ? [e.clientX, e.clientY]
358 : [e.changedTouches[0].pageX, e.changedTouches[0].pageY];
359 let landing = document.elementFromPoint(offsetX, offsetY);
360 this.selectedPiece.style.zIndex = 3000;
361 // Next condition: classList.contains(piece) fails because of marks
362 while (landing.tagName == "IMG") landing = landing.parentNode;
363 if (this.start.id == landing.id)
364 // One or multi clicks on same piece
365 return;
366 // OK: process move attempt, landing is a square node
367 let endSquare = getSquareFromId(landing.id);
368 let moves = this.findMatchingMoves(endSquare);
369 this.possibleMoves = [];
370 if (moves.length > 1) this.choices = moves;
371 else if (moves.length == 1) this.play(moves[0]);
372 // Else: impossible move
373 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
374 delete this.selectedPiece;
375 this.selectedPiece = null;
376 },
377 findMatchingMoves: function(endSquare) {
378 // Run through moves list and return the matching set (if promotions...)
379 let moves = [];
380 this.possibleMoves.forEach(function(m) {
381 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y) moves.push(m);
382 });
383 return moves;
384 },
385 play: function(move) {
386 this.$emit("play-move", move);
387 }
388 }
389 };
390 </script>
391
392 <style lang="sass" scoped>
393 .game.reserve-div
394 margin-bottom: 18px
395
396 .reserve-count
397 padding-left: 40%
398
399 .reserve-row-1
400 margin-bottom: 15px
401
402 // NOTE: no variants with reserve of size != 8
403
404 .game
405 width: 100%
406 margin: 0
407 .board
408 cursor: pointer
409
410 #choices
411 margin: 0
412 position: absolute
413 z-index: 300
414 overflow-y: inherit
415 background-color: rgba(0,0,0,0)
416 img
417 cursor: pointer
418 background-color: #e6ee9c
419 &:hover
420 background-color: skyblue
421 &.choice-piece
422 width: 100%
423 height: auto
424 display: block
425
426 img.ghost
427 position: absolute
428 opacity: 0.4
429 top: 0
430
431 .highlight-light
432 background-color: rgba(0, 204, 102, 0.7) !important
433 .highlight-dark
434 background-color: rgba(0, 204, 102, 0.9) !important
435
436 .incheck-light
437 background-color: rgba(204, 51, 0, 0.7) !important
438 .incheck-dark
439 background-color: rgba(204, 51, 0, 0.9) !important
440
441 .light-square.lichess
442 background-color: #f0d9b5;
443 .dark-square.lichess
444 background-color: #b58863;
445
446 .light-square.chesscom
447 background-color: #e5e5ca;
448 .dark-square.chesscom
449 background-color: #6f8f57;
450
451 .light-square.chesstempo
452 background-color: #fdfdfd;
453 .dark-square.chesstempo
454 background-color: #88a0a8;
455 </style>