Add Koopa chess, fix Apocalypse and Dice variants
[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)
107dc1bd 25 containerPos: null,
cf2343ce 26 selectedPiece: null, //moving piece (or clicked piece)
28b32b4f 27 start: null, //pixels coordinates + id of starting square (click or drag)
49dad261 28 startArrow: null,
107dc1bd 29 movingArrow: null,
49dad261
BA
30 arrows: [], //object of {start: x,y / end: x,y}
31 circles: {}, //object of squares' ID --> true (TODO: use a set?)
28b32b4f 32 click: "",
3a2a7b5f 33 clickTime: 0,
6808d7a1 34 settings: store.state.settings
cf2343ce
BA
35 };
36 },
37 render(h) {
6808d7a1 38 if (!this.vr) {
7b3cf1b7 39 // Return empty div of class 'game' to avoid error when setting size
107dc1bd
BA
40 return h(
41 "div",
42 { "class": { game: true } }
43 );
7b3cf1b7 44 }
6808d7a1 45 const [sizeX, sizeY] = [V.size.x, V.size.y];
cf2343ce 46 // Precompute hints squares to facilitate rendering
e2732923 47 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
6808d7a1
BA
48 this.possibleMoves.forEach(m => {
49 hintSquares[m.end.x][m.end.y] = true;
50 });
cf2343ce 51 // Also precompute in-check squares
e2732923 52 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
6808d7a1
BA
53 this.incheck.forEach(sq => {
54 incheckSq[sq[0]][sq[1]] = true;
55 });
06e79b07 56
af34341d
BA
57 let lm = this.lastMove;
58 // Precompute lastMove highlighting squares
59 const lmHighlights = {};
60 if (!!lm) {
61 if (!Array.isArray(lm)) lm = [lm];
62 lm.forEach(m => {
00eef1ca 63 if (!m.start.noHighlight && V.OnBoard(m.start.x, m.start.y))
b406466b 64 lmHighlights[m.start.x + sizeX * m.start.y] = true;
00eef1ca 65 if (!m.end.noHighlight && V.OnBoard(m.end.x, m.end.y))
b406466b 66 lmHighlights[m.end.x + sizeX * m.end.y] = true;
6e0f2842
BA
67 if (!!m.start.toplay)
68 // For Dice variant (at least?)
69 lmHighlights[m.start.toplay[0] + sizeX * m.start.toplay[1]] = true;
af34341d
BA
70 });
71 }
57eb158f
BA
72 const showLight = (
73 this.settings.highlight &&
4f524197 74 ["all", "highlight"].includes(V.ShowMoves)
57eb158f 75 );
d54f6261
BA
76 const showCheck = (
77 this.settings.highlight &&
4f524197 78 ["all", "highlight", "byrow"].includes(V.ShowMoves)
d54f6261 79 );
311cba76
BA
80 const orientation = !V.CanFlip ? "w" : this.orientation;
81 // Ensure that squares colors do not change when board is flipped
82 const lightSquareMod = (sizeX + sizeY) % 2;
83 const showPiece = (x, y) => {
84 return (
85 this.vr.board[x][y] != V.EMPTY &&
86 (!this.vr.enlightened || this.analyze || this.score != "*" ||
87 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
88 );
89 };
90 const inHighlight = (x, y) => {
af34341d 91 return showLight && !!lmHighlights[x + sizeX * y];
311cba76
BA
92 };
93 const inShadow = (x, y) => {
94 return (
95 !this.analyze &&
96 this.score == "*" &&
97 this.vr.enlightened &&
98 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
99 );
100 };
101 // Create board element (+ reserves if needed by variant)
9d4a0218 102 let elementArray = [];
cf2343ce 103 const gameDiv = h(
6808d7a1 104 "div",
cf2343ce 105 {
107dc1bd 106 attrs: { id: "gamePosition" },
6ec2feb2 107 "class": {
6808d7a1
BA
108 game: true,
109 clearer: true
110 }
cf2343ce
BA
111 },
112 [...Array(sizeX).keys()].map(i => {
311cba76 113 const ci = orientation == "w" ? i : sizeX - i - 1;
cf2343ce 114 return h(
6808d7a1 115 "div",
cf2343ce 116 {
6ec2feb2 117 "class": {
6808d7a1 118 row: true
cf2343ce 119 },
6808d7a1 120 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
cf2343ce
BA
121 },
122 [...Array(sizeY).keys()].map(j => {
311cba76 123 const cj = orientation == "w" ? j : sizeY - j - 1;
49dad261 124 const squareId = "sq-" + ci + "-" + cj;
cf2343ce 125 let elems = [];
311cba76 126 if (showPiece(ci, cj)) {
ffeaef85
BA
127 let pieceSpecs = {
128 "class": {
129 piece: true,
130 ghost:
131 !!this.selectedPiece &&
132 this.selectedPiece.parentNode.id == squareId
133 },
134 attrs: {
135 src:
136 "/images/pieces/" +
137 this.vr.getPpath(
138 this.vr.board[ci][cj],
139 // Extra args useful for some variants:
140 this.userColor,
141 this.score,
142 this.orientation) +
143 V.IMAGE_EXTENSION
144 }
145 };
146 if (this.arrows.length == 0)
147 pieceSpecs["style"] = { position: "absolute" };
148 elems.push(h("img", pieceSpecs));
cf2343ce 149 }
6808d7a1 150 if (this.settings.hints && hintSquares[ci][cj]) {
cf2343ce 151 elems.push(
6808d7a1 152 h("img", {
6ec2feb2 153 "class": {
6808d7a1
BA
154 "mark-square": true
155 },
156 attrs: {
157 src: "/images/mark.svg"
cf2343ce 158 }
6808d7a1 159 })
cf2343ce
BA
160 );
161 }
49dad261
BA
162 if (!!this.circles[squareId]) {
163 elems.push(
164 h("img", {
165 "class": {
166 "circle-square": true
167 },
168 attrs: {
169 src: "/images/circle.svg"
170 }
171 })
172 );
173 }
311cba76 174 const lightSquare = (ci + cj) % 2 == lightSquareMod;
cf2343ce 175 return h(
6808d7a1 176 "div",
cf2343ce 177 {
6ec2feb2 178 "class": {
6808d7a1
BA
179 board: true,
180 ["board" + sizeY]: true,
ffeaef85
BA
181 "light-square":
182 !V.Notoodark && lightSquare && !V.Monochrome,
183 "dark-square":
184 !V.Notoodark && (!lightSquare || !!V.Monochrome),
185 "middle-square": V.Notoodark,
dfeb96ea 186 [this.settings.bcolor]: true,
311cba76
BA
187 "in-shadow": inShadow(ci, cj),
188 "highlight-light": inHighlight(ci, cj) && lightSquare,
ffeaef85
BA
189 "highlight-dark":
190 inHighlight(ci, cj) && (V.Monochrome || !lightSquare),
2c5d7b20
BA
191 "incheck-light":
192 showCheck && lightSquare && incheckSq[ci][cj],
193 "incheck-dark":
90df90bc
BA
194 showCheck && !lightSquare && incheckSq[ci][cj],
195 "hover-highlight": this.vr.hoverHighlight(ci, cj)
cf2343ce
BA
196 },
197 attrs: {
6808d7a1
BA
198 id: getSquareId({ x: ci, y: cj })
199 }
cf2343ce
BA
200 },
201 elems
202 );
203 })
204 );
24340cae 205 })
cf2343ce 206 );
9d4a0218
BA
207 if (!!this.vr.reserve) {
208 const playingColor = this.userColor || "w"; //default for an observer
6808d7a1 209 const shiftIdx = playingColor == "w" ? 0 : 1;
107dc1bd
BA
210 // Some variants have more than sizeY reserve pieces (Clorange: 10)
211 const reserveSquareNb = Math.max(sizeY, V.RESERVE_PIECES.length);
cf2343ce 212 let myReservePiecesArray = [];
6808d7a1 213 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
9d4a0218 214 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
6808d7a1
BA
215 myReservePiecesArray.push(
216 h(
217 "div",
218 {
107dc1bd 219 "class": { board: true, ["board" + reserveSquareNb]: true },
9d4a0218
BA
220 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
221 style: { opacity: qty > 0 ? 1 : 0.35 }
6808d7a1
BA
222 },
223 [
224 h("img", {
ffeaef85 225 // NOTE: class "reserve" not used currently
6ec2feb2 226 "class": { piece: true, reserve: true },
6808d7a1
BA
227 attrs: {
228 src:
229 "/images/pieces/" +
cd49e617 230 this.vr.getReservePpath(i, playingColor, orientation) +
6808d7a1
BA
231 ".svg"
232 }
233 }),
ffeaef85
BA
234 h(
235 "sup",
236 {
237 "class": { "reserve-count": true },
238 style: { top: "calc(100% + 5px)" }
239 },
240 [ qty ]
241 )
6808d7a1 242 ]
cf2343ce 243 )
6808d7a1 244 );
cf2343ce
BA
245 }
246 let oppReservePiecesArray = [];
93d1d7a7 247 const oppCol = V.GetOppCol(playingColor);
6808d7a1 248 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
9d4a0218 249 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
6808d7a1
BA
250 oppReservePiecesArray.push(
251 h(
252 "div",
253 {
107dc1bd 254 "class": { board: true, ["board" + reserveSquareNb]: true },
9d4a0218
BA
255 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
256 style: { opacity: qty > 0 ? 1 : 0.35 }
6808d7a1
BA
257 },
258 [
259 h("img", {
6ec2feb2 260 "class": { piece: true, reserve: true },
6808d7a1
BA
261 attrs: {
262 src:
263 "/images/pieces/" +
cd49e617 264 this.vr.getReservePpath(i, oppCol, orientation) +
6808d7a1
BA
265 ".svg"
266 }
267 }),
ffeaef85
BA
268 h(
269 "sup",
270 {
271 "class": { "reserve-count": true },
272 style: { top: "calc(100% + 5px)" }
273 },
274 [ qty ]
275 )
6808d7a1 276 ]
cf2343ce 277 )
6808d7a1 278 );
cf2343ce 279 }
9d4a0218
BA
280 const myReserveTop = (
281 (playingColor == 'w' && orientation == 'b') ||
282 (playingColor == 'b' && orientation == 'w')
cf2343ce 283 );
9d4a0218
BA
284 // Center reserves, assuming same number of pieces for each side:
285 const nbReservePieces = myReservePiecesArray.length;
107dc1bd
BA
286 const marginLeft =
287 ((100 - nbReservePieces * (100 / reserveSquareNb)) / 2) + "%";
9d4a0218
BA
288 const reserveTop =
289 h(
290 "div",
291 {
6ec2feb2 292 "class": {
9d4a0218
BA
293 game: true,
294 "reserve-div": true
295 },
296 style: {
297 "margin-left": marginLeft
298 }
299 },
300 [
301 h(
302 "div",
303 {
6ec2feb2 304 "class": {
9d4a0218
BA
305 row: true,
306 "reserve-row": true
307 }
308 },
309 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
310 )
311 ]
312 );
313 var reserveBottom =
314 h(
315 "div",
316 {
6ec2feb2 317 "class": {
9d4a0218
BA
318 game: true,
319 "reserve-div": true
320 },
321 style: {
322 "margin-left": marginLeft
323 }
324 },
325 [
326 h(
327 "div",
328 {
6ec2feb2 329 "class": {
9d4a0218
BA
330 row: true,
331 "reserve-row": true
332 }
333 },
334 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
335 )
336 ]
337 );
338 elementArray.push(reserveTop);
cf2343ce 339 }
9d4a0218
BA
340 elementArray.push(gameDiv);
341 if (!!this.vr.reserve) elementArray.push(reserveBottom);
107dc1bd
BA
342 const boardElt = document.getElementById("gamePosition");
343 // boardElt might be undefine (at first drawing)
6808d7a1 344 if (this.choices.length > 0 && !!boardElt) {
107dc1bd 345 const squareWidth = boardElt.offsetWidth / sizeY;
aafe9f16 346 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
14edde72
BA
347 const maxNbeltsPerRow = Math.min(this.choices.length, sizeY);
348 let topOffset = offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2;
349 let choicesHeight = squareWidth;
350 if (this.choices.length >= sizeY) {
351 // A second row is required (Eightpieces variant)
352 topOffset -= squareWidth / 2;
353 choicesHeight *= 2;
354 }
aafe9f16 355 const choices = h(
6808d7a1 356 "div",
aafe9f16 357 {
6808d7a1 358 attrs: { id: "choices" },
6ec2feb2 359 "class": { row: true },
aafe9f16 360 style: {
14edde72 361 top: topOffset + "px",
6808d7a1
BA
362 left:
363 offset[1] +
14edde72 364 (squareWidth * Math.max(sizeY - this.choices.length, 0)) / 2 +
6808d7a1 365 "px",
14edde72
BA
366 width: (maxNbeltsPerRow * squareWidth) + "px",
367 height: choicesHeight + "px"
6808d7a1 368 }
aafe9f16 369 },
14edde72
BA
370 [ h(
371 "div",
6ec2feb2
BA
372 {
373 "class": { "full-width": true }
374 },
14edde72
BA
375 this.choices.map(m => {
376 // A "choice" is a move
377 const applyMove = (e) => {
378 e.stopPropagation();
379 // Force a delay between move is shown and clicked
380 // (otherwise a "double-click" bug might occur)
381 if (Date.now() - this.clickTime < 200) return;
14edde72 382 this.choices = [];
78c23cd6 383 this.play(m);
14edde72
BA
384 };
385 const onClick =
386 this.mobileBrowser
387 ? { touchend: applyMove }
388 : { mouseup: applyMove };
389 return h(
390 "div",
391 {
6ec2feb2 392 "class": {
14edde72
BA
393 board: true,
394 ["board" + sizeY]: true
aafe9f16 395 },
14edde72
BA
396 style: {
397 width: (100 / maxNbeltsPerRow) + "%",
398 "padding-bottom": (100 / maxNbeltsPerRow) + "%"
399 }
400 },
401 [
402 h("img", {
403 attrs: {
404 src:
405 "/images/pieces/" +
c7550017
BA
406 // orientation: extra arg useful for some variants:
407 this.vr.getPPpath(m, this.orientation) +
14edde72
BA
408 V.IMAGE_EXTENSION
409 },
6ec2feb2 410 "class": { "choice-piece": true },
14edde72
BA
411 on: onClick
412 })
413 ]
414 );
415 })
416 ) ]
aafe9f16
BA
417 );
418 elementArray.unshift(choices);
419 }
4b26ecb8
BA
420 let onEvents = {};
421 // NOTE: click = mousedown + mouseup
cafe0166 422 if (this.mobileBrowser) {
4b26ecb8
BA
423 onEvents = {
424 on: {
425 touchstart: this.mousedown,
426 touchmove: this.mousemove,
6808d7a1
BA
427 touchend: this.mouseup
428 }
4b26ecb8 429 };
6808d7a1 430 } else {
4b26ecb8 431 onEvents = {
cf2343ce 432 on: {
65495c17
BA
433 mousedown: this.mousedown,
434 mousemove: this.mousemove,
49dad261
BA
435 mouseup: this.mouseup,
436 contextmenu: this.blockContextMenu
6808d7a1 437 }
4b26ecb8
BA
438 };
439 }
107dc1bd
BA
440 return (
441 h(
442 "div",
443 Object.assign({ attrs: { id: "rootBoardElement" } }, onEvents),
444 elementArray
445 )
446 );
447 },
448 updated: function() {
449 this.re_setDrawings();
cf2343ce
BA
450 },
451 methods: {
49dad261
BA
452 blockContextMenu: function(e) {
453 e.preventDefault();
454 e.stopPropagation();
455 return false;
456 },
457 cancelResetArrows: function() {
458 this.startArrow = null;
459 this.arrows = [];
460 this.circles = {};
107dc1bd
BA
461 const curCanvas = document.getElementById("arrowCanvas");
462 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
463 },
464 coordsToXY: function(coords, top, left, squareWidth) {
465 return {
466 // [1] for x and [0] for y because conventions in rules are inversed.
467 x: (
468 left + window.scrollX +
469 (
470 squareWidth *
471 (this.orientation == 'w' ? coords[1] : (V.size.y - coords[1]))
472 )
473 ),
474 y: (
475 top + window.scrollY +
476 (
477 squareWidth *
478 (this.orientation == 'w' ? coords[0] : (V.size.x - coords[0]))
479 )
480 )
481 };
49dad261 482 },
107dc1bd
BA
483 computeEndArrow: function(start, end, top, left, squareWidth) {
484 const endCoords = this.coordsToXY(end, top, left, squareWidth);
485 const delta = [endCoords.x - start.x, endCoords.y - start.y];
486 const dist = Math.sqrt(delta[0] * delta[0] + delta[1] * delta[1]);
cd049aa1
BA
487 // Simple heuristic for now, just remove 1/3 square.
488 // TODO: should depend on the orientation.
cd049aa1
BA
489 const fracSqWidth = squareWidth / 3;
490 return {
107dc1bd
BA
491 x: endCoords.x - delta[0] * fracSqWidth / dist,
492 y: endCoords.y - delta[1] * fracSqWidth / dist
cd049aa1
BA
493 };
494 },
107dc1bd
BA
495 drawCurrentArrow: function() {
496 const boardElt = document.getElementById("gamePosition");
497 const squareWidth = boardElt.offsetWidth / V.size.y;
498 const bPos = boardElt.getBoundingClientRect();
499 const aStart =
500 this.coordsToXY(
501 [this.startArrow[0] + 0.5, this.startArrow[1] + 0.5],
502 bPos.top, bPos.left, squareWidth);
503 const aEnd =
504 this.computeEndArrow(
505 aStart, [this.movingArrow[0] + 0.5, this.movingArrow[1] + 0.5],
506 bPos.top, bPos.left, squareWidth);
507 let currentArrow = document.getElementById("currentArrow");
508 const d =
509 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y;
510 const arrowWidth = squareWidth / 4;
511 if (!!currentArrow) currentArrow.setAttribute("d", d);
512 else {
513 let domArrow =
514 document.createElementNS("http://www.w3.org/2000/svg", "path");
515 domArrow.classList.add("svg-arrow");
516 domArrow.id = "currentArrow";
517 domArrow.setAttribute("d", d);
518 domArrow.style = "stroke-width:" + arrowWidth + "px";
519 document.getElementById("arrowCanvas")
520 .insertAdjacentElement("beforeend", domArrow);
521 }
522 },
523 addArrow: function(arrow) {
524 this.arrows.push(arrow);
525 // Also add to DOM:
526 const boardElt = document.getElementById("gamePosition");
527 const squareWidth = boardElt.offsetWidth / V.size.y;
528 const bPos = boardElt.getBoundingClientRect();
529 const newArrow =
530 this.getSvgArrow(arrow, bPos.top, bPos.left, squareWidth);
531 document.getElementById("arrowCanvas")
532 .insertAdjacentElement("beforeend", newArrow);
533 },
534 getSvgArrow: function(arrow, top, left, squareWidth) {
535 const aStart =
536 this.coordsToXY(
537 [arrow.start[0] + 0.5, arrow.start[1] + 0.5],
538 top, left, squareWidth);
539 const aEnd =
540 this.computeEndArrow(
541 aStart, [arrow.end[0] + 0.5, arrow.end[1] + 0.5],
542 top, left, squareWidth);
543 const arrowWidth = squareWidth / 4;
544 let path =
545 document.createElementNS("http://www.w3.org/2000/svg", "path");
546 path.classList.add("svg-arrow");
547 path.setAttribute(
548 "d",
549 "M" + aStart.x + "," + aStart.y + " " + "L" + aEnd.x + "," + aEnd.y
550 );
551 path.style = "stroke-width:" + arrowWidth + "px";
552 return path;
553 },
554 re_setDrawings: function() {
555 // Remove current canvas, if any
556 const curCanvas = document.getElementById("arrowCanvas");
557 if (!!curCanvas) curCanvas.parentNode.removeChild(curCanvas);
558 // Add some drawing on board (for some variants + arrows and circles)
559 const boardElt = document.getElementById("gamePosition");
560 const squareWidth = boardElt.offsetWidth / V.size.y;
561 const bPos = boardElt.getBoundingClientRect();
562 let svgArrows = [];
563 this.arrows.forEach(a => {
564 svgArrows.push(this.getSvgArrow(a, bPos.top, bPos.left, squareWidth));
565 });
566 let vLines = [];
567 if (!!V.Lines) {
568 V.Lines.forEach(line => {
569 const lStart =
570 this.coordsToXY(line[0], bPos.top, bPos.left, squareWidth);
571 const lEnd =
572 this.coordsToXY(line[1], bPos.top, bPos.left, squareWidth);
573 let path =
574 document.createElementNS("http://www.w3.org/2000/svg", "path");
8efb985e
BA
575 if (line[0][0] == line[1][0] || line[0][1] == line[1][1])
576 path.classList.add("svg-line");
577 else
578 // "Diagonals" are drawn with a lighter color (TODO: generalize)
579 path.classList.add("svg-diag");
107dc1bd
BA
580 path.setAttribute(
581 "d",
582 "M" + lStart.x + "," + lStart.y + " " +
583 "L" + lEnd.x + "," + lEnd.y
584 );
585 vLines.push(path);
586 });
587 }
588 let arrowCanvas =
589 document.createElementNS("http://www.w3.org/2000/svg", "svg");
590 arrowCanvas.id = "arrowCanvas";
591 arrowCanvas.setAttribute("stroke", "none");
592 let defs =
593 document.createElementNS("http://www.w3.org/2000/svg", "defs");
594 const arrowWidth = squareWidth / 4;
595 let marker =
596 document.createElementNS("http://www.w3.org/2000/svg", "marker");
597 marker.id = "arrow";
598 marker.setAttribute("markerWidth", (2 * arrowWidth) + "px");
599 marker.setAttribute("markerHeight", (3 * arrowWidth) + "px");
600 marker.setAttribute("markerUnits", "userSpaceOnUse");
601 marker.setAttribute("refX", "0");
602 marker.setAttribute("refY", (1.5 * arrowWidth) + "px");
603 marker.setAttribute("orient", "auto");
604 let head =
605 document.createElementNS("http://www.w3.org/2000/svg", "path");
606 head.classList.add("arrow-head");
607 head.setAttribute(
608 "d",
609 "M0,0 L0," + (3 * arrowWidth) + " L" +
610 (2 * arrowWidth) + "," + (1.5 * arrowWidth) + " z"
611 );
612 marker.appendChild(head);
613 defs.appendChild(marker);
614 arrowCanvas.appendChild(defs);
615 svgArrows.concat(vLines).forEach(av => arrowCanvas.appendChild(av));
616 document.getElementById("rootBoardElement").appendChild(arrowCanvas);
617 },
cf2343ce 618 mousedown: function(e) {
28b32b4f 619 e.preventDefault();
1ef65040 620 if (!this.mobileBrowser && e.which != 3)
49dad261
BA
621 // Cancel current drawing and circles, if any
622 this.cancelResetArrows();
1ef65040 623 if (this.mobileBrowser || e.which == 1) {
49dad261
BA
624 // Mouse left button
625 if (!this.start) {
8764102a
BA
626 this.containerPos =
627 document.getElementById("boardContainer").getBoundingClientRect();
49dad261
BA
628 // NOTE: classList[0] is enough: 'piece' is the first assigned class
629 const withPiece = (e.target.classList[0] == "piece");
630 // Emit the click event which could be used by some variants
631 this.$emit(
632 "click-square",
633 getSquareFromId(withPiece ? e.target.parentNode.id : e.target.id)
634 );
635 // Start square must contain a piece.
636 if (!withPiece) return;
637 let parent = e.target.parentNode; //surrounding square
638 // Show possible moves if current player allowed to play
639 const startSquare = getSquareFromId(parent.id);
640 this.possibleMoves = [];
641 const color = this.analyze ? this.vr.turn : this.userColor;
642 if (this.vr.canIplay(color, startSquare))
643 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
596e24d0 644 else return;
49dad261
BA
645 // For potential drag'n drop, remember start coordinates
646 // (to center the piece on mouse cursor)
647 const rect = parent.getBoundingClientRect();
648 this.start = {
649 x: rect.x + rect.width / 2,
650 y: rect.y + rect.width / 2,
651 id: parent.id
652 };
653 // Add the moving piece to the board, just after current image
654 this.selectedPiece = e.target.cloneNode();
655 Object.assign(
656 this.selectedPiece.style,
657 {
658 position: "absolute",
659 top: 0,
660 display: "inline-block",
661 zIndex: 3000
662 }
663 );
664 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
665 } else {
666 this.processMoveAttempt(e);
667 }
1ef65040
BA
668 } else if (e.which == 3) {
669 // Mouse right button
8764102a
BA
670 this.containerPos =
671 document.getElementById("gamePosition").getBoundingClientRect();
49dad261
BA
672 let elem = e.target;
673 // Next loop because of potential marks
674 while (elem.tagName == "IMG") elem = elem.parentNode;
107dc1bd 675 this.startArrow = getSquareFromId(elem.id);
49dad261
BA
676 }
677 },
678 mousemove: function(e) {
679 if (!this.selectedPiece && !this.startArrow) return;
107dc1bd
BA
680 // Cancel if off boardContainer
681 const [offsetX, offsetY] =
682 this.mobileBrowser
10addfff 683 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
107dc1bd
BA
684 : [e.clientX, e.clientY];
685 if (
686 offsetX < this.containerPos.left ||
687 offsetX > this.containerPos.right ||
688 offsetY < this.containerPos.top ||
689 offsetY > this.containerPos.bottom
690 ) {
8764102a
BA
691 if (!!this.selectedPiece) {
692 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
693 delete this.selectedPiece;
694 this.selectedPiece = null;
695 this.start = null;
85b6326c
BA
696 this.possibleMoves = []; //in case of
697 this.click = "";
8764102a
BA
698 let selected = document.querySelector(".ghost");
699 if (!!selected) selected.classList.remove("ghost");
700 }
701 else {
702 this.startArrow = null;
703 this.movingArrow = null;
704 const currentArrow = document.getElementById("currentArrow");
705 if (!!currentArrow)
706 currentArrow.parentNode.removeChild(currentArrow);
707 }
107dc1bd
BA
708 return;
709 }
49dad261
BA
710 e.preventDefault();
711 if (!!this.selectedPiece) {
712 // There is an active element: move it around
28b32b4f
BA
713 Object.assign(
714 this.selectedPiece.style,
715 {
49dad261
BA
716 left: offsetX - this.start.x + "px",
717 top: offsetY - this.start.y + "px"
28b32b4f
BA
718 }
719 );
28b32b4f 720 }
49dad261
BA
721 else {
722 let elem = e.target;
723 // Next loop because of potential marks
724 while (elem.tagName == "IMG") elem = elem.parentNode;
725 // To center the arrow in square:
107dc1bd
BA
726 const movingCoords = getSquareFromId(elem.id);
727 if (
728 movingCoords[0] != this.startArrow[0] ||
729 movingCoords[1] != this.startArrow[1]
730 ) {
731 this.movingArrow = movingCoords;
732 this.drawCurrentArrow();
28b32b4f 733 }
49dad261 734 }
cf2343ce
BA
735 },
736 mouseup: function(e) {
28b32b4f 737 e.preventDefault();
1ef65040 738 if (this.mobileBrowser || e.which == 1) {
49dad261
BA
739 if (!this.selectedPiece) return;
740 // Drag'n drop. Selected piece is no longer needed:
741 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
742 delete this.selectedPiece;
743 this.selectedPiece = null;
744 this.processMoveAttempt(e);
1ef65040 745 } else if (e.which == 3) {
8764102a 746 if (!this.startArrow) return;
1ef65040 747 // Mouse right button
107dc1bd 748 this.movingArrow = null;
49dad261
BA
749 this.processArrowAttempt(e);
750 }
28b32b4f 751 },
e90bafa8
BA
752 // Called by BaseGame after partially undoing multi-moves:
753 resetCurrentAttempt: function() {
754 this.possibleMoves = [];
755 this.start = null;
756 this.click = "";
757 this.selectedPiece = null;
758 },
28b32b4f
BA
759 processMoveAttempt: function(e) {
760 // Obtain the move from start and end squares
cafe0166
BA
761 const [offsetX, offsetY] =
762 this.mobileBrowser
10addfff 763 ? [e.changedTouches[0].clientX, e.changedTouches[0].clientY]
cafe0166 764 : [e.clientX, e.clientY];
cf2343ce 765 let landing = document.elementFromPoint(offsetX, offsetY);
cf2343ce 766 // Next condition: classList.contains(piece) fails because of marks
6808d7a1 767 while (landing.tagName == "IMG") landing = landing.parentNode;
28b32b4f
BA
768 if (this.start.id == landing.id) {
769 if (this.click == landing.id) {
770 // Second click on same square: cancel current move
771 this.possibleMoves = [];
772 this.start = null;
773 this.click = "";
774 } else this.click = landing.id;
cf2343ce 775 return;
28b32b4f
BA
776 }
777 this.start = null;
bd76b456 778 // OK: process move attempt, landing is a square node
cf2343ce
BA
779 let endSquare = getSquareFromId(landing.id);
780 let moves = this.findMatchingMoves(endSquare);
781 this.possibleMoves = [];
3a2a7b5f
BA
782 if (moves.length > 1) {
783 this.clickTime = Date.now();
784 this.choices = moves;
785 } else if (moves.length == 1) this.play(moves[0]);
28b32b4f 786 // else: forbidden move attempt
cf2343ce 787 },
49dad261
BA
788 processArrowAttempt: function(e) {
789 // Obtain the arrow from start and end squares
790 const [offsetX, offsetY] = [e.clientX, e.clientY];
791 let landing = document.elementFromPoint(offsetX, offsetY);
792 // Next condition: classList.contains(piece) fails because of marks
793 while (landing.tagName == "IMG") landing = landing.parentNode;
107dc1bd
BA
794 const landingCoords = getSquareFromId(landing.id);
795 if (
796 this.startArrow[0] == landingCoords[0] &&
797 this.startArrow[1] == landingCoords[1]
798 ) {
49dad261
BA
799 // Draw (or erase) a circle
800 this.$set(this.circles, landing.id, !this.circles[landing.id]);
107dc1bd 801 }
49dad261
BA
802 else {
803 // OK: add arrow, landing is a new square
107dc1bd
BA
804 const currentArrow = document.getElementById("currentArrow");
805 currentArrow.parentNode.removeChild(currentArrow);
806 this.addArrow({
807 start: this.startArrow,
808 end: landingCoords
49dad261
BA
809 });
810 }
811 this.startArrow = null;
812 },
cf2343ce
BA
813 findMatchingMoves: function(endSquare) {
814 // Run through moves list and return the matching set (if promotions...)
28b32b4f
BA
815 return (
816 this.possibleMoves.filter(m => {
817 return (endSquare[0] == m.end.x && endSquare[1] == m.end.y);
818 })
819 );
cf2343ce
BA
820 },
821 play: function(move) {
6808d7a1
BA
822 this.$emit("play-move", move);
823 }
824 }
cf2343ce
BA
825};
826</script>
4473050c 827
107dc1bd
BA
828<style lang="sass">
829// SVG dynamically added, so not scoped
830#arrowCanvas
831 pointer-events: none
832 position: absolute
833 top: 0
834 left: 0
835 width: 100%
836 height: 100%
837
838.svg-arrow
839 opacity: 0.65
840 stroke: #5f0e78
841 fill: none
842 marker-end: url(#arrow)
843
844.svg-line
845 stroke: black
846
8efb985e
BA
847.svg-diag
848 stroke: grey
849
107dc1bd
BA
850.arrow-head
851 fill: #5f0e78
852</style>
853
41c80bb6 854<style lang="sass" scoped>
26d8a01a
BA
855@import "@/styles/_board_squares_img.sass";
856
ffeaef85
BA
857//.game.reserve-div
858 // TODO: would be cleaner to restrict width so that it doesn't overflow
859 // Commented out because pieces would disappear over the board otherwise:
860 //overflow: hidden
50aed5a1 861.reserve-count
ffeaef85
BA
862 width: 100%
863 text-align: center
864 display: inline-block
865 position: absolute
9d4a0218 866.reserve-row
50aed5a1
BA
867 margin-bottom: 15px
868
6ec2feb2
BA
869.full-width
870 width: 100%
41cb9b94 871
50aed5a1 872.game
28b32b4f 873 user-select: none
cf94b843
BA
874 width: 100%
875 margin: 0
50aed5a1
BA
876 .board
877 cursor: pointer
50aed5a1
BA
878
879#choices
28b32b4f 880 user-select: none
168a5e4c
BA
881 margin: 0
882 position: absolute
50aed5a1
BA
883 z-index: 300
884 overflow-y: inherit
885 background-color: rgba(0,0,0,0)
886 img
887 cursor: pointer
888 background-color: #e6ee9c
889 &:hover
890 background-color: skyblue
891 &.choice-piece
892 width: 100%
893 height: auto
894 display: block
895
50aed5a1 896img.ghost
ffeaef85 897 // NOTE: no need to set z-index here, since opacity is low
50aed5a1 898 position: absolute
28b32b4f 899 opacity: 0.5
50aed5a1
BA
900 top: 0
901
311cba76
BA
902.incheck-light
903 background-color: rgba(204, 51, 0, 0.7) !important
904.incheck-dark
905 background-color: rgba(204, 51, 0, 0.9) !important
50aed5a1 906
28b32b4f
BA
907// TODO: no predefined highlight colors, but layers. How?
908
90df90bc
BA
909.hover-highlight:hover
910 // TODO: color dependant on board theme, or inner border...
00eef1ca 911 background-color: #C571E6 !important
90df90bc 912
28b32b4f 913.light-square.lichess.highlight-light
b0a0468a 914 background-color: #cdd26a
28b32b4f 915.dark-square.lichess.highlight-dark
b0a0468a 916 background-color: #aaa23a
28b32b4f
BA
917
918.light-square.chesscom.highlight-light
b0a0468a 919 background-color: #f7f783
28b32b4f 920.dark-square.chesscom.highlight-dark
b0a0468a 921 background-color: #bacb44
28b32b4f
BA
922
923.light-square.chesstempo.highlight-light
b0a0468a 924 background-color: #9f9fff
28b32b4f 925.dark-square.chesstempo.highlight-dark
b0a0468a 926 background-color: #557fff
baa6f86f
BA
927
928.light-square.orangecc.highlight-light
929 background-color: #fef273
930.dark-square.orangecc.highlight-dark
931 background-color: #e8c525
4473050c 932</style>