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