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