Better Ball rules. Buggish but almost OK Synchrone variant
[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",
cf2343ce
BA
7 // Last move cannot be guessed from here, and is required to highlight squares
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 {
6808d7a1
BA
90 class: {
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 {
6808d7a1
BA
100 class: {
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
BA
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/" +
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
BA
133 h("img", {
134 class: {
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 {
6808d7a1
BA
147 class: {
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,
d54f6261
BA
156 "incheck-light": showCheck && lightSquare && incheckSq[ci][cj],
157 "incheck-dark": showCheck && !lightSquare && incheckSq[ci][cj]
cf2343ce
BA
158 },
159 attrs: {
6808d7a1
BA
160 id: getSquareId({ x: ci, y: cj })
161 }
cf2343ce
BA
162 },
163 elems
164 );
165 })
166 );
24340cae 167 })
cf2343ce 168 );
9d4a0218
BA
169 if (!!this.vr.reserve) {
170 const playingColor = this.userColor || "w"; //default for an observer
6808d7a1 171 const shiftIdx = playingColor == "w" ? 0 : 1;
cf2343ce 172 let myReservePiecesArray = [];
6808d7a1 173 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
9d4a0218 174 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
6808d7a1
BA
175 myReservePiecesArray.push(
176 h(
177 "div",
178 {
179 class: { board: true, ["board" + sizeY]: true },
9d4a0218
BA
180 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
181 style: { opacity: qty > 0 ? 1 : 0.35 }
6808d7a1
BA
182 },
183 [
184 h("img", {
185 class: { piece: true, reserve: true },
186 attrs: {
187 src:
188 "/images/pieces/" +
241bf8f2 189 this.vr.getReservePpath(i, playingColor) +
6808d7a1
BA
190 ".svg"
191 }
192 }),
9d4a0218 193 h("sup", { class: { "reserve-count": true } }, [ qty ])
6808d7a1 194 ]
cf2343ce 195 )
6808d7a1 196 );
cf2343ce
BA
197 }
198 let oppReservePiecesArray = [];
93d1d7a7 199 const oppCol = V.GetOppCol(playingColor);
6808d7a1 200 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
9d4a0218 201 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
6808d7a1
BA
202 oppReservePiecesArray.push(
203 h(
204 "div",
205 {
206 class: { board: true, ["board" + sizeY]: true },
9d4a0218
BA
207 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
208 style: { opacity: qty > 0 ? 1 : 0.35 }
6808d7a1
BA
209 },
210 [
211 h("img", {
212 class: { piece: true, reserve: true },
213 attrs: {
214 src:
215 "/images/pieces/" +
241bf8f2 216 this.vr.getReservePpath(i, oppCol) +
6808d7a1
BA
217 ".svg"
218 }
219 }),
9d4a0218 220 h("sup", { class: { "reserve-count": true } }, [ qty ])
6808d7a1 221 ]
cf2343ce 222 )
6808d7a1 223 );
cf2343ce 224 }
9d4a0218
BA
225 const myReserveTop = (
226 (playingColor == 'w' && orientation == 'b') ||
227 (playingColor == 'b' && orientation == 'w')
cf2343ce 228 );
9d4a0218
BA
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);
cf2343ce 283 }
9d4a0218
BA
284 elementArray.push(gameDiv);
285 if (!!this.vr.reserve) elementArray.push(reserveBottom);
aafe9f16 286 const boardElt = document.querySelector(".game");
6808d7a1 287 if (this.choices.length > 0 && !!boardElt) {
afbf3ca7 288 // No choices to show at first drawing
aafe9f16
BA
289 const squareWidth = boardElt.offsetWidth / sizeY;
290 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
14edde72
BA
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 }
aafe9f16 299 const choices = h(
6808d7a1 300 "div",
aafe9f16 301 {
6808d7a1
BA
302 attrs: { id: "choices" },
303 class: { row: true },
aafe9f16 304 style: {
14edde72 305 top: topOffset + "px",
6808d7a1
BA
306 left:
307 offset[1] +
14edde72 308 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
6808d7a1 309 "px",
14edde72
BA
310 width: (maxNbeltsPerRow * squareWidth) + "px",
311 height: choicesHeight + "px"
6808d7a1 312 }
aafe9f16 313 },
14edde72
BA
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;
14edde72 324 this.choices = [];
78c23cd6 325 this.play(m);
14edde72
BA
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
aafe9f16 337 },
14edde72
BA
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 ) ]
aafe9f16
BA
361 );
362 elementArray.unshift(choices);
363 }
4b26ecb8
BA
364 let onEvents = {};
365 // NOTE: click = mousedown + mouseup
cafe0166 366 if (this.mobileBrowser) {
4b26ecb8
BA
367 onEvents = {
368 on: {
369 touchstart: this.mousedown,
370 touchmove: this.mousemove,
6808d7a1
BA
371 touchend: this.mouseup
372 }
4b26ecb8 373 };
6808d7a1 374 } else {
4b26ecb8 375 onEvents = {
cf2343ce 376 on: {
65495c17
BA
377 mousedown: this.mousedown,
378 mousemove: this.mousemove,
6808d7a1
BA
379 mouseup: this.mouseup
380 }
4b26ecb8
BA
381 };
382 }
6808d7a1 383 return h("div", onEvents, elementArray);
cf2343ce
BA
384 },
385 methods: {
386 mousedown: function(e) {
28b32b4f
BA
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 }
cf2343ce
BA
422 },
423 mousemove: function(e) {
6808d7a1 424 if (!this.selectedPiece) return;
28b32b4f 425 e.preventDefault();
aafe9f16 426 // There is an active element: move it around
cafe0166
BA
427 const [offsetX, offsetY] =
428 this.mobileBrowser
429 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
430 : [e.clientX, e.clientY];
28b32b4f
BA
431 Object.assign(
432 this.selectedPiece.style,
433 {
434 left: offsetX - this.start.x + "px",
435 top: offsetY - this.start.y + "px"
436 }
437 );
cf2343ce
BA
438 },
439 mouseup: function(e) {
6808d7a1 440 if (!this.selectedPiece) return;
28b32b4f
BA
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
cafe0166
BA
450 const [offsetX, offsetY] =
451 this.mobileBrowser
452 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
453 : [e.clientX, e.clientY];
cf2343ce 454 let landing = document.elementFromPoint(offsetX, offsetY);
cf2343ce 455 // Next condition: classList.contains(piece) fails because of marks
6808d7a1 456 while (landing.tagName == "IMG") landing = landing.parentNode;
28b32b4f
BA
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;
cf2343ce 464 return;
28b32b4f
BA
465 }
466 this.start = null;
bd76b456 467 // OK: process move attempt, landing is a square node
cf2343ce
BA
468 let endSquare = getSquareFromId(landing.id);
469 let moves = this.findMatchingMoves(endSquare);
470 this.possibleMoves = [];
3a2a7b5f
BA
471 if (moves.length > 1) {
472 this.clickTime = Date.now();
473 this.choices = moves;
474 } else if (moves.length == 1) this.play(moves[0]);
28b32b4f 475 // else: forbidden move attempt
cf2343ce
BA
476 },
477 findMatchingMoves: function(endSquare) {
478 // Run through moves list and return the matching set (if promotions...)
28b32b4f
BA
479 return (
480 this.possibleMoves.filter(m => {
481 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
482 })
483 );
cf2343ce
BA
484 },
485 play: function(move) {
6808d7a1
BA
486 this.$emit("play-move", move);
487 }
488 }
cf2343ce
BA
489};
490</script>
4473050c 491
41c80bb6 492<style lang="sass" scoped>
50aed5a1
BA
493.game.reserve-div
494 margin-bottom: 18px
495
496.reserve-count
497 padding-left: 40%
498
9d4a0218 499.reserve-row
50aed5a1
BA
500 margin-bottom: 15px
501
41cb9b94
BA
502// NOTE: no variants with reserve of size != 8
503
50aed5a1 504.game
28b32b4f 505 user-select: none
cf94b843
BA
506 width: 100%
507 margin: 0
50aed5a1
BA
508 .board
509 cursor: pointer
50aed5a1
BA
510
511#choices
28b32b4f 512 user-select: none
168a5e4c
BA
513 margin: 0
514 position: absolute
50aed5a1
BA
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
50aed5a1
BA
528img.ghost
529 position: absolute
28b32b4f 530 opacity: 0.5
50aed5a1
BA
531 top: 0
532
311cba76
BA
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
50aed5a1
BA
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
28b32b4f 549 background-color: #dfdfdf;
50aed5a1 550.dark-square.chesstempo
28b32b4f
BA
551 background-color: #7287b6;
552
553// TODO: no predefined highlight colors, but layers. How?
554
555.light-square.lichess.highlight-light
b0a0468a 556 background-color: #cdd26a
28b32b4f 557.dark-square.lichess.highlight-dark
b0a0468a 558 background-color: #aaa23a
28b32b4f
BA
559
560.light-square.chesscom.highlight-light
b0a0468a 561 background-color: #f7f783
28b32b4f 562.dark-square.chesscom.highlight-dark
b0a0468a 563 background-color: #bacb44
28b32b4f
BA
564
565.light-square.chesstempo.highlight-light
b0a0468a 566 background-color: #9f9fff
28b32b4f 567.dark-square.chesstempo.highlight-dark
b0a0468a 568 background-color: #557fff
28b32b4f 569
4473050c 570</style>