'update'
[vchess.git] / client / src / components / Board.vue
CommitLineData
24340cae 1<script>
e2732923
BA
2import { getSquareId, getSquareFromId } from "@/utils/squareId";
3import { ArrayFun } from "@/utils/array";
dfeb96ea 4import { store } from "@/store";
cf2343ce
BA
5export 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...
93d1d7a7 9 // userColor is left undefined for an external observer
f51c37cf 10 props: ["vr","lastMove","analyze","incheck","orientation","userColor","vname"],
cf2343ce
BA
11 data: function () {
12 return {
cf2343ce
BA
13 possibleMoves: [], //filled after each valid click/dragstart
14 choices: [], //promotion pieces, or checkered captures... (as moves)
15 selectedPiece: null, //moving piece (or clicked piece)
cf2343ce 16 start: {}, //pixels coordinates + id of starting square (click or drag)
dfeb96ea 17 settings: store.state.settings,
cf2343ce
BA
18 };
19 },
20 render(h) {
21 if (!this.vr)
7b3cf1b7
BA
22 {
23 // Return empty div of class 'game' to avoid error when setting size
24 return h("div",
25 {
26 "class": {
27 "game": true,
28 },
29 });
30 }
cf2343ce
BA
31 const [sizeX,sizeY] = [V.size.x,V.size.y];
32 // Precompute hints squares to facilitate rendering
e2732923 33 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
cf2343ce
BA
34 this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
35 // Also precompute in-check squares
e2732923 36 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
cf2343ce 37 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
06e79b07 38
7b3cf1b7
BA
39 let boardElt = document.querySelector(".game");
40 const squareWidth = (!!boardElt
41 ? boardElt.offsetWidth / sizeY
06e79b07 42 : 40); //arbitrary value (not relevant)
168a5e4c
BA
43 const offset = (!!boardElt
44 ? [boardElt.offsetTop, boardElt.offsetLeft]
45 : [0, 0]);
cf2343ce
BA
46 const choices = h(
47 'div',
48 {
49 attrs: { "id": "choices" },
50 'class': { 'row': true },
51 style: {
93d1d7a7 52 "display": (this.choices.length > 0 ? "block" : "none"),
168a5e4c
BA
53 "top": (offset[0] + (sizeY/2)*squareWidth-squareWidth/2) + "px",
54 "left": (offset[1] + squareWidth*(sizeY - this.choices.length)/2) + "px",
cf2343ce
BA
55 "width": (this.choices.length * squareWidth) + "px",
56 "height": squareWidth + "px",
57 },
58 },
59 this.choices.map(m => { //a "choice" is a move
60 return h('div',
61 {
62 'class': {
63 'board': true,
64 ['board'+sizeY]: true,
65 },
66 style: {
67 'width': (100/this.choices.length) + "%",
68 'padding-bottom': (100/this.choices.length) + "%",
69 },
70 },
71 [h('img',
72 {
73 attrs: { "src": '/images/pieces/' +
74 V.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
75 'class': { 'choice-piece': true },
76 on: {
77 "click": e => { this.play(m); this.choices=[]; },
78 // NOTE: add 'touchstart' event to fix a problem on smartphones
79 "touchstart": e => { this.play(m); this.choices=[]; },
80 },
81 })
82 ]
83 );
84 })
85 );
86 // Create board element (+ reserves if needed by variant or mode)
87 const lm = this.lastMove;
dfeb96ea 88 const showLight = this.settings.highlight && this.vname != "Dark";
cf2343ce
BA
89 const gameDiv = h(
90 'div',
91 {
92 'class': {
93 'game': true,
94 'clearer': true,
95 },
96 },
97 [...Array(sizeX).keys()].map(i => {
98 let ci = (this.orientation=='w' ? i : sizeX-i-1);
99 return h(
100 'div',
101 {
102 'class': {
103 'row': true,
104 },
105 style: { 'opacity': this.choices.length>0?"0.5":"1" },
106 },
107 [...Array(sizeY).keys()].map(j => {
108 let cj = (this.orientation=='w' ? j : sizeY-j-1);
109 let elems = [];
e2732923 110 if (this.vr.board[ci][cj] != V.EMPTY && (this.vname!="Dark"
93d1d7a7
BA
111 || this.analyze || (!!this.userColor
112 && this.vr.enlightened[this.userColor][ci][cj])))
cf2343ce
BA
113 {
114 elems.push(
115 h(
116 'img',
117 {
118 'class': {
119 'piece': true,
120 'ghost': !!this.selectedPiece
121 && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
122 },
123 attrs: {
50aed5a1
BA
124 src: "/images/pieces/" +
125 V.getPpath(this.vr.board[ci][cj]) + ".svg",
cf2343ce
BA
126 },
127 }
128 )
129 );
130 }
dfeb96ea 131 if (this.settings.hints && hintSquares[ci][cj])
cf2343ce
BA
132 {
133 elems.push(
134 h(
135 'img',
136 {
137 'class': {
138 'mark-square': true,
139 },
140 attrs: {
141 src: "/images/mark.svg",
142 },
143 }
144 )
145 );
146 }
147 return h(
148 'div',
149 {
150 'class': {
151 'board': true,
152 ['board'+sizeY]: true,
153 'light-square': (i+j)%2==0,
154 'dark-square': (i+j)%2==1,
dfeb96ea 155 [this.settings.bcolor]: true,
93d1d7a7
BA
156 'in-shadow': this.vname=="Dark" && !this.analyze
157 && (!this.userColor
158 || !this.vr.enlightened[this.userColor][ci][cj]),
cf2343ce
BA
159 'highlight': showLight && !!lm && lm.end.x == ci && lm.end.y == cj,
160 'incheck': showLight && incheckSq[ci][cj],
161 },
162 attrs: {
163 id: getSquareId({x:ci,y:cj}),
164 },
165 },
166 elems
167 );
168 })
169 );
24340cae 170 })
cf2343ce 171 );
d4036efe 172 const playingColor = this.userColor || "w"; //default for an observer
cf2343ce
BA
173 let elementArray = [choices, gameDiv];
174 if (!!this.vr.reserve)
175 {
93d1d7a7 176 const shiftIdx = (playingColor=="w" ? 0 : 1);
cf2343ce
BA
177 let myReservePiecesArray = [];
178 for (let i=0; i<V.RESERVE_PIECES.length; i++)
179 {
180 myReservePiecesArray.push(h('div',
181 {
182 'class': {'board':true, ['board'+sizeY]:true},
183 attrs: { id: getSquareId({x:sizeX+shiftIdx,y:i}) }
184 },
185 [
186 h('img',
187 {
188 'class': {"piece":true, "reserve":true},
189 attrs: {
190 "src": "/images/pieces/" +
93d1d7a7 191 this.vr.getReservePpath(playingColor,i) + ".svg",
cf2343ce
BA
192 }
193 }),
194 h('sup',
195 {"class": { "reserve-count": true } },
93d1d7a7 196 [ this.vr.reserve[playingColor][V.RESERVE_PIECES[i]] ]
cf2343ce
BA
197 )
198 ]));
199 }
200 let oppReservePiecesArray = [];
93d1d7a7 201 const oppCol = V.GetOppCol(playingColor);
cf2343ce
BA
202 for (let i=0; i<V.RESERVE_PIECES.length; i++)
203 {
204 oppReservePiecesArray.push(h('div',
205 {
206 'class': {'board':true, ['board'+sizeY]:true},
207 attrs: { id: getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
208 },
209 [
210 h('img',
211 {
212 'class': {"piece":true, "reserve":true},
213 attrs: {
214 "src": "/images/pieces/" +
215 this.vr.getReservePpath(oppCol,i) + ".svg",
216 }
217 }),
218 h('sup',
219 {"class": { "reserve-count": true } },
220 [ this.vr.reserve[oppCol][V.RESERVE_PIECES[i]] ]
221 )
222 ]));
223 }
224 let reserves = h('div',
225 {
226 'class':{
227 'game': true,
228 "reserve-div": true,
229 },
230 },
231 [
232 h('div',
233 {
234 'class': {
235 'row': true,
236 "reserve-row-1": true,
237 },
238 },
239 myReservePiecesArray
240 ),
241 h('div',
242 { 'class': { 'row': true }},
243 oppReservePiecesArray
244 )
245 ]
246 );
247 elementArray.push(reserves);
248 }
249 return h(
250 'div',
251 {
cf2343ce
BA
252 // NOTE: click = mousedown + mouseup
253 on: {
254 mousedown: this.mousedown,
255 mousemove: this.mousemove,
256 mouseup: this.mouseup,
257 touchstart: this.mousedown,
258 touchmove: this.mousemove,
259 touchend: this.mouseup,
260 },
261 },
262 elementArray
263 );
264 },
265 methods: {
266 mousedown: function(e) {
267 e = e || window.event;
268 let ingame = false;
269 let elem = e.target;
270 while (!ingame && elem !== null)
271 {
272 if (elem.classList.contains("game"))
273 {
274 ingame = true;
275 break;
276 }
277 elem = elem.parentElement;
278 }
279 if (!ingame) //let default behavior (click on button...)
280 return;
281 e.preventDefault(); //disable native drag & drop
282 if (!this.selectedPiece && e.target.classList.contains("piece"))
283 {
284 // Next few lines to center the piece on mouse cursor
285 let rect = e.target.parentNode.getBoundingClientRect();
286 this.start = {
287 x: rect.x + rect.width/2,
288 y: rect.y + rect.width/2,
289 id: e.target.parentNode.id
290 };
291 this.selectedPiece = e.target.cloneNode();
292 this.selectedPiece.style.position = "absolute";
293 this.selectedPiece.style.top = 0;
294 this.selectedPiece.style.display = "inline-block";
295 this.selectedPiece.style.zIndex = 3000;
296 const startSquare = getSquareFromId(e.target.parentNode.id);
297 this.possibleMoves = [];
93d1d7a7 298 const color = (this.analyze ? this.vr.turn : this.userColor);
cf2343ce
BA
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>
4473050c 367
41c80bb6 368<style lang="sass" scoped>
50aed5a1
BA
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
41cb9b94
BA
378// NOTE: no variants with reserve of size != 8
379
50aed5a1
BA
380div.board
381 float: left
382 height: 0
383 display: inline-block
384 position: relative
385
386div.board8
387 width: 12.5%
388 padding-bottom: 12.5%
389
390div.board10
391 width: 10%
392 padding-bottom: 10%
393
394div.board11
395 width: 9.09%
396 padding-bottom: 9.1%
397
50aed5a1 398.game
cf94b843
BA
399 width: 100%
400 margin: 0
50aed5a1
BA
401 .board
402 cursor: pointer
50aed5a1
BA
403
404#choices
168a5e4c
BA
405 margin: 0
406 position: absolute
50aed5a1
BA
407 z-index: 300
408 overflow-y: inherit
409 background-color: rgba(0,0,0,0)
410 img
411 cursor: pointer
412 background-color: #e6ee9c
413 &:hover
414 background-color: skyblue
415 &.choice-piece
416 width: 100%
417 height: auto
418 display: block
419
420img.piece
421 width: 100%
422
423img.piece, img.mark-square
424 max-width: 100%
425 height: auto
426 display: block
427
428img.mark-square
429 opacity: 0.6
430 width: 76%
431 position: absolute
432 top: 12%
433 left: 12%
434 opacity: .7
435
436img.ghost
437 position: absolute
438 opacity: 0.4
439 top: 0
440
441.highlight
442 background-color: #00cc66 !important
443
444.in-shadow
445 filter: brightness(50%)
446
447.incheck
448 background-color: #cc3300 !important
449
450.light-square.lichess
451 background-color: #f0d9b5;
452.dark-square.lichess
453 background-color: #b58863;
454
455.light-square.chesscom
456 background-color: #e5e5ca;
457.dark-square.chesscom
458 background-color: #6f8f57;
459
460.light-square.chesstempo
461 background-color: #fdfdfd;
462.dark-square.chesstempo
463 background-color: #88a0a8;
4473050c 464</style>