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