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