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