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