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