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