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