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