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