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