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