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