Cosmetics
[vchess.git] / client / src / components / Board.vue
... / ...
CommitLineData
1<script>
2import { getSquareId, getSquareFromId } from "@/utils/squareId";
3import { ArrayFun } from "@/utils/array";
4import { store } from "@/store";
5export default {
6 name: "my-board",
7 // Last move cannot be guessed from here, and is required to highlight squares
8 // vr: object to check moves, print board...
9 // userColor is left undefined for an external observer
10 props: [
11 "vr",
12 "lastMove",
13 "analyze",
14 "score",
15 "incheck",
16 "orientation",
17 "userColor",
18 "vname"
19 ],
20 data: function() {
21 return {
22 mobileBrowser: ("ontouchstart" in window),
23 possibleMoves: [], //filled after each valid click/dragstart
24 choices: [], //promotion pieces, or checkered captures... (as moves)
25 selectedPiece: null, //moving piece (or clicked piece)
26 start: {}, //pixels coordinates + id of starting square (click or drag)
27 settings: store.state.settings
28 };
29 },
30 render(h) {
31 if (!this.vr) {
32 // Return empty div of class 'game' to avoid error when setting size
33 return h("div", {
34 class: {
35 game: true
36 }
37 });
38 }
39 const [sizeX, sizeY] = [V.size.x, V.size.y];
40 // Precompute hints squares to facilitate rendering
41 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
42 this.possibleMoves.forEach(m => {
43 hintSquares[m.end.x][m.end.y] = true;
44 });
45 // Also precompute in-check squares
46 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
47 this.incheck.forEach(sq => {
48 incheckSq[sq[0]][sq[1]] = true;
49 });
50
51 const lm = this.lastMove;
52 const showLight = (
53 this.settings.highlight &&
54 ["all","highlight"].includes(V.ShowMoves)
55 );
56 const orientation = !V.CanFlip ? "w" : this.orientation;
57 // Ensure that squares colors do not change when board is flipped
58 const lightSquareMod = (sizeX + sizeY) % 2;
59 const showPiece = (x, y) => {
60 return (
61 this.vr.board[x][y] != V.EMPTY &&
62 (!this.vr.enlightened || this.analyze || this.score != "*" ||
63 (!!this.userColor && this.vr.enlightened[this.userColor][x][y]))
64 );
65 };
66 const inHighlight = (x, y) => {
67 return showLight && !!lm && (
68 (lm.end.x == x && lm.end.y == y) ||
69 (lm.start.x == x && lm.start.y == y));
70 };
71 const inShadow = (x, y) => {
72 return (
73 !this.analyze &&
74 this.score == "*" &&
75 this.vr.enlightened &&
76 (!this.userColor || !this.vr.enlightened[this.userColor][x][y])
77 );
78 };
79 // Create board element (+ reserves if needed by variant)
80 let elementArray = [];
81 const gameDiv = h(
82 "div",
83 {
84 class: {
85 game: true,
86 clearer: true
87 }
88 },
89 [...Array(sizeX).keys()].map(i => {
90 const ci = orientation == "w" ? i : sizeX - i - 1;
91 return h(
92 "div",
93 {
94 class: {
95 row: true
96 },
97 style: { opacity: this.choices.length > 0 ? "0.5" : "1" }
98 },
99 [...Array(sizeY).keys()].map(j => {
100 const cj = orientation == "w" ? j : sizeY - j - 1;
101 let elems = [];
102 if (showPiece(ci, cj)) {
103 elems.push(
104 h("img", {
105 class: {
106 piece: true,
107 ghost:
108 !!this.selectedPiece &&
109 this.selectedPiece.parentNode.id == "sq-" + ci + "-" + cj
110 },
111 attrs: {
112 src:
113 "/images/pieces/" +
114 this.vr.getPpath(this.vr.board[ci][cj], this.userColor, this.score) +
115 ".svg"
116 }
117 })
118 );
119 }
120 if (this.settings.hints && hintSquares[ci][cj]) {
121 elems.push(
122 h("img", {
123 class: {
124 "mark-square": true
125 },
126 attrs: {
127 src: "/images/mark.svg"
128 }
129 })
130 );
131 }
132 const lightSquare = (ci + cj) % 2 == lightSquareMod;
133 return h(
134 "div",
135 {
136 class: {
137 board: true,
138 ["board" + sizeY]: true,
139 "light-square": lightSquare,
140 "dark-square": !lightSquare,
141 [this.settings.bcolor]: true,
142 "in-shadow": inShadow(ci, cj),
143 "highlight-light": inHighlight(ci, cj) && lightSquare,
144 "highlight-dark": inHighlight(ci, cj) && !lightSquare,
145 "incheck-light": showLight && lightSquare && incheckSq[ci][cj],
146 "incheck-dark": showLight && !lightSquare && incheckSq[ci][cj]
147 },
148 attrs: {
149 id: getSquareId({ x: ci, y: cj })
150 }
151 },
152 elems
153 );
154 })
155 );
156 })
157 );
158 if (!!this.vr.reserve) {
159 const playingColor = this.userColor || "w"; //default for an observer
160 const shiftIdx = playingColor == "w" ? 0 : 1;
161 let myReservePiecesArray = [];
162 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
163 const qty = this.vr.reserve[playingColor][V.RESERVE_PIECES[i]];
164 myReservePiecesArray.push(
165 h(
166 "div",
167 {
168 class: { board: true, ["board" + sizeY]: true },
169 attrs: { id: getSquareId({ x: sizeX + shiftIdx, y: i }) },
170 style: { opacity: qty > 0 ? 1 : 0.35 }
171 },
172 [
173 h("img", {
174 class: { piece: true, reserve: true },
175 attrs: {
176 src:
177 "/images/pieces/" +
178 this.vr.getReservePpath(i, playingColor) +
179 ".svg"
180 }
181 }),
182 h("sup", { class: { "reserve-count": true } }, [ qty ])
183 ]
184 )
185 );
186 }
187 let oppReservePiecesArray = [];
188 const oppCol = V.GetOppCol(playingColor);
189 for (let i = 0; i < V.RESERVE_PIECES.length; i++) {
190 const qty = this.vr.reserve[oppCol][V.RESERVE_PIECES[i]];
191 oppReservePiecesArray.push(
192 h(
193 "div",
194 {
195 class: { board: true, ["board" + sizeY]: true },
196 attrs: { id: getSquareId({ x: sizeX + (1 - shiftIdx), y: i }) },
197 style: { opacity: qty > 0 ? 1 : 0.35 }
198 },
199 [
200 h("img", {
201 class: { piece: true, reserve: true },
202 attrs: {
203 src:
204 "/images/pieces/" +
205 this.vr.getReservePpath(i, oppCol) +
206 ".svg"
207 }
208 }),
209 h("sup", { class: { "reserve-count": true } }, [ qty ])
210 ]
211 )
212 );
213 }
214 const myReserveTop = (
215 (playingColor == 'w' && orientation == 'b') ||
216 (playingColor == 'b' && orientation == 'w')
217 );
218 // Center reserves, assuming same number of pieces for each side:
219 const nbReservePieces = myReservePiecesArray.length;
220 const marginLeft = ((100 - nbReservePieces * (100 / sizeY)) / 2) + "%";
221 const reserveTop =
222 h(
223 "div",
224 {
225 class: {
226 game: true,
227 "reserve-div": true
228 },
229 style: {
230 "margin-left": marginLeft
231 }
232 },
233 [
234 h(
235 "div",
236 {
237 class: {
238 row: true,
239 "reserve-row": true
240 }
241 },
242 myReserveTop ? myReservePiecesArray : oppReservePiecesArray
243 )
244 ]
245 );
246 var reserveBottom =
247 h(
248 "div",
249 {
250 class: {
251 game: true,
252 "reserve-div": true
253 },
254 style: {
255 "margin-left": marginLeft
256 }
257 },
258 [
259 h(
260 "div",
261 {
262 class: {
263 row: true,
264 "reserve-row": true
265 }
266 },
267 myReserveTop ? oppReservePiecesArray : myReservePiecesArray
268 )
269 ]
270 );
271 elementArray.push(reserveTop);
272 }
273 elementArray.push(gameDiv);
274 if (!!this.vr.reserve) elementArray.push(reserveBottom);
275 const boardElt = document.querySelector(".game");
276 if (this.choices.length > 0 && !!boardElt) {
277 //no choices to show at first drawing
278 const squareWidth = boardElt.offsetWidth / sizeY;
279 const offset = [boardElt.offsetTop, boardElt.offsetLeft];
280 const choices = h(
281 "div",
282 {
283 attrs: { id: "choices" },
284 class: { row: true },
285 style: {
286 top: offset[0] + (sizeY / 2) * squareWidth - squareWidth / 2 + "px",
287 left:
288 offset[1] +
289 (squareWidth * (sizeY - this.choices.length)) / 2 +
290 "px",
291 width: this.choices.length * squareWidth + "px",
292 height: squareWidth + "px"
293 }
294 },
295 this.choices.map(m => {
296 //a "choice" is a move
297 return h(
298 "div",
299 {
300 class: {
301 board: true,
302 ["board" + sizeY]: true
303 },
304 style: {
305 width: 100 / this.choices.length + "%",
306 "padding-bottom": 100 / this.choices.length + "%"
307 }
308 },
309 [
310 h("img", {
311 attrs: {
312 src:
313 "/images/pieces/" +
314 this.vr.getPpath(m.appear[0].c + m.appear[0].p) +
315 ".svg"
316 },
317 class: { "choice-piece": true },
318 on: {
319 click: () => {
320 this.play(m);
321 this.choices = [];
322 }
323 }
324 })
325 ]
326 );
327 })
328 );
329 elementArray.unshift(choices);
330 }
331 let onEvents = {};
332 // NOTE: click = mousedown + mouseup
333 if (this.mobileBrowser) {
334 onEvents = {
335 on: {
336 touchstart: this.mousedown,
337 touchmove: this.mousemove,
338 touchend: this.mouseup
339 }
340 };
341 } else {
342 onEvents = {
343 on: {
344 mousedown: this.mousedown,
345 mousemove: this.mousemove,
346 mouseup: this.mouseup
347 }
348 };
349 }
350 return h("div", onEvents, elementArray);
351 },
352 methods: {
353 mousedown: function(e) {
354 // Abort if a piece is already being processed, or target is not a piece.
355 // NOTE: just looking at classList[0] because piece is the first assigned class
356 if (!!this.selectedPiece || e.target.classList[0] != "piece") return;
357 e.preventDefault(); //disable native drag & drop
358 let parent = e.target.parentNode; //the surrounding square
359 // Next few lines to center the piece on mouse cursor
360 let rect = parent.getBoundingClientRect();
361 this.start = {
362 x: rect.x + rect.width / 2,
363 y: rect.y + rect.width / 2,
364 id: parent.id
365 };
366 this.selectedPiece = e.target.cloneNode();
367 let spStyle = this.selectedPiece.style;
368 spStyle.position = "absolute";
369 spStyle.top = 0;
370 spStyle.display = "inline-block";
371 spStyle.zIndex = 3000;
372 const startSquare = getSquareFromId(parent.id);
373 this.possibleMoves = [];
374 const color = this.analyze ? this.vr.turn : this.userColor;
375 if (this.vr.canIplay(color, startSquare))
376 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
377 // Next line add moving piece just after current image
378 // (required for Crazyhouse reserve)
379 parent.insertBefore(this.selectedPiece, e.target.nextSibling);
380 },
381 mousemove: function(e) {
382 if (!this.selectedPiece) return;
383 // There is an active element: move it around
384 const [offsetX, offsetY] =
385 this.mobileBrowser
386 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
387 : [e.clientX, e.clientY];
388 this.selectedPiece.style.left = offsetX - this.start.x + "px";
389 this.selectedPiece.style.top = offsetY - this.start.y + "px";
390 },
391 mouseup: function(e) {
392 if (!this.selectedPiece) return;
393 // There is an active element: obtain the move from start and end squares
394 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coords
395 const [offsetX, offsetY] =
396 this.mobileBrowser
397 ? [e.changedTouches[0].pageX, e.changedTouches[0].pageY]
398 : [e.clientX, e.clientY];
399 let landing = document.elementFromPoint(offsetX, offsetY);
400 this.selectedPiece.style.zIndex = 3000;
401 // Next condition: classList.contains(piece) fails because of marks
402 while (landing.tagName == "IMG") landing = landing.parentNode;
403 if (this.start.id == landing.id)
404 // One or multi clicks on same piece
405 return;
406 // OK: process move attempt, landing is a square node
407 let endSquare = getSquareFromId(landing.id);
408 let moves = this.findMatchingMoves(endSquare);
409 this.possibleMoves = [];
410 if (moves.length > 1) this.choices = moves;
411 else if (moves.length == 1) this.play(moves[0]);
412 // Else: impossible move
413 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
414 delete this.selectedPiece;
415 this.selectedPiece = null;
416 },
417 findMatchingMoves: function(endSquare) {
418 // Run through moves list and return the matching set (if promotions...)
419 let moves = [];
420 this.possibleMoves.forEach(function(m) {
421 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y) moves.push(m);
422 });
423 return moves;
424 },
425 play: function(move) {
426 this.$emit("play-move", move);
427 }
428 }
429};
430</script>
431
432<style lang="sass" scoped>
433.game.reserve-div
434 margin-bottom: 18px
435
436.reserve-count
437 padding-left: 40%
438
439.reserve-row
440 margin-bottom: 15px
441
442// NOTE: no variants with reserve of size != 8
443
444.game
445 width: 100%
446 margin: 0
447 .board
448 cursor: pointer
449
450#choices
451 margin: 0
452 position: absolute
453 z-index: 300
454 overflow-y: inherit
455 background-color: rgba(0,0,0,0)
456 img
457 cursor: pointer
458 background-color: #e6ee9c
459 &:hover
460 background-color: skyblue
461 &.choice-piece
462 width: 100%
463 height: auto
464 display: block
465
466img.ghost
467 position: absolute
468 opacity: 0.4
469 top: 0
470
471.highlight-light
472 background-color: rgba(0, 204, 102, 0.7) !important
473.highlight-dark
474 background-color: rgba(0, 204, 102, 0.9) !important
475
476.incheck-light
477 background-color: rgba(204, 51, 0, 0.7) !important
478.incheck-dark
479 background-color: rgba(204, 51, 0, 0.9) !important
480
481.light-square.lichess
482 background-color: #f0d9b5;
483.dark-square.lichess
484 background-color: #b58863;
485
486.light-square.chesscom
487 background-color: #e5e5ca;
488.dark-square.chesscom
489 background-color: #6f8f57;
490
491.light-square.chesstempo
492 background-color: #fdfdfd;
493.dark-square.chesstempo
494 background-color: #88a0a8;
495</style>