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