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