2 // This can work for squared boards (2 or 4 players), with some adaptations (TODO)
3 // TODO: for 3 players, write a "board3.js"
5 import { getSquareId, getSquareFromId } from "@/utils/squareId";
6 import { ArrayFun } from "@/utils/array";
10 // Last move cannot be guessed from here, and is required to highlight squares
11 // vr: object to check moves, print board...
12 // mode: HH, HC or analyze
13 // userColor: for mode HH or HC
14 props: ["vr","lastMove","mode","orientation","userColor","vname"],
17 hints: (!localStorage["hints"] ? true : localStorage["hints"] === "1"),
18 bcolor: localStorage["bcolor"] || "lichess", //lichess, chesscom or chesstempo
19 possibleMoves: [], //filled after each valid click/dragstart
20 choices: [], //promotion pieces, or checkered captures... (as moves)
21 selectedPiece: null, //moving piece (or clicked piece)
23 start: {}, //pixels coordinates + id of starting square (click or drag)
29 const [sizeX,sizeY] = [V.size.x,V.size.y];
30 // Precompute hints squares to facilitate rendering
31 let hintSquares = ArrayFun.init(sizeX, sizeY, false);
32 this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
33 // Also precompute in-check squares
34 let incheckSq = ArrayFun.init(sizeX, sizeY, false);
35 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
36 const squareWidth = 40; //TODO: compute this
40 attrs: { "id": "choices" },
41 'class': { 'row': true },
43 "display": this.choices.length>0?"block":"none",
44 "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
45 "width": (this.choices.length * squareWidth) + "px",
46 "height": squareWidth + "px",
49 this.choices.map(m => { //a "choice" is a move
54 ['board'+sizeY]: true,
57 'width': (100/this.choices.length) + "%",
58 'padding-bottom': (100/this.choices.length) + "%",
63 attrs: { "src": '/images/pieces/' +
64 V.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
65 'class': { 'choice-piece': true },
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=[]; },
76 // Create board element (+ reserves if needed by variant or mode)
77 const lm = this.lastMove;
78 const showLight = this.hints && this.vname != "Dark";
87 [...Array(sizeX).keys()].map(i => {
88 let ci = (this.orientation=='w' ? i : sizeX-i-1);
95 style: { 'opacity': this.choices.length>0?"0.5":"1" },
97 [...Array(sizeY).keys()].map(j => {
98 let cj = (this.orientation=='w' ? j : sizeY-j-1);
100 if (this.vr.board[ci][cj] != V.EMPTY && (this.vname!="Dark"
101 || this.gameOver || this.mode == "analyze"
102 || this.vr.enlightened[this.userColor][ci][cj]))
110 'ghost': !!this.selectedPiece
111 && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
114 src: require("@/assets/images/pieces/" +
115 V.getPpath(this.vr.board[ci][cj]) + ".svg"),
121 if (this.hints && hintSquares[ci][cj])
131 src: "/images/mark.svg",
142 ['board'+sizeY]: true,
143 'light-square': (i+j)%2==0,
144 'dark-square': (i+j)%2==1,
146 'in-shadow': this.vname=="Dark" && !this.gameOver
147 && this.mode != "analyze"
148 && !this.vr.enlightened[this.userColor][ci][cj],
149 'highlight': showLight && !!lm && lm.end.x == ci && lm.end.y == cj,
150 'incheck': showLight && incheckSq[ci][cj],
153 id: getSquareId({x:ci,y:cj}),
162 let elementArray = [choices, gameDiv];
163 if (!!this.vr.reserve)
165 const shiftIdx = (this.userColor=="w" ? 0 : 1);
166 let myReservePiecesArray = [];
167 for (let i=0; i<V.RESERVE_PIECES.length; i++)
169 myReservePiecesArray.push(h('div',
171 'class': {'board':true, ['board'+sizeY]:true},
172 attrs: { id: getSquareId({x:sizeX+shiftIdx,y:i}) }
177 'class': {"piece":true, "reserve":true},
179 "src": "/images/pieces/" +
180 this.vr.getReservePpath(this.userColor,i) + ".svg",
184 {"class": { "reserve-count": true } },
185 [ this.vr.reserve[this.userColor][V.RESERVE_PIECES[i]] ]
189 let oppReservePiecesArray = [];
190 const oppCol = V.GetOppCol(this.userColor);
191 for (let i=0; i<V.RESERVE_PIECES.length; i++)
193 oppReservePiecesArray.push(h('div',
195 'class': {'board':true, ['board'+sizeY]:true},
196 attrs: { id: getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
201 'class': {"piece":true, "reserve":true},
203 "src": "/images/pieces/" +
204 this.vr.getReservePpath(oppCol,i) + ".svg",
208 {"class": { "reserve-count": true } },
209 [ this.vr.reserve[oppCol][V.RESERVE_PIECES[i]] ]
213 let reserves = h('div',
225 "reserve-row-1": true,
231 { 'class': { 'row': true }},
232 oppReservePiecesArray
236 elementArray.push(reserves);
244 "col-md-offset-1": true,
246 "col-lg-offset-2": true,
248 // NOTE: click = mousedown + mouseup
250 mousedown: this.mousedown,
251 mousemove: this.mousemove,
252 mouseup: this.mouseup,
253 touchstart: this.mousedown,
254 touchmove: this.mousemove,
255 touchend: this.mouseup,
262 mousedown: function(e) {
263 e = e || window.event;
266 while (!ingame && elem !== null)
268 if (elem.classList.contains("game"))
273 elem = elem.parentElement;
275 if (!ingame) //let default behavior (click on button...)
277 e.preventDefault(); //disable native drag & drop
278 if (!this.selectedPiece && e.target.classList.contains("piece"))
280 // Next few lines to center the piece on mouse cursor
281 let rect = e.target.parentNode.getBoundingClientRect();
283 x: rect.x + rect.width/2,
284 y: rect.y + rect.width/2,
285 id: e.target.parentNode.id
287 this.selectedPiece = e.target.cloneNode();
288 this.selectedPiece.style.position = "absolute";
289 this.selectedPiece.style.top = 0;
290 this.selectedPiece.style.display = "inline-block";
291 this.selectedPiece.style.zIndex = 3000;
292 const startSquare = getSquareFromId(e.target.parentNode.id);
293 this.possibleMoves = [];
294 const color = this.mode=="analyze" || this.gameOver
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);
304 mousemove: function(e) {
305 if (!this.selectedPiece)
307 e = e || window.event;
308 // If there is an active element, move it around
309 if (!!this.selectedPiece)
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";
318 mouseup: function(e) {
319 if (!this.selectedPiece)
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)
334 // A click: selectedPiece and possibleMoves are already filled
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)
345 // Else: impossible move
346 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
347 delete this.selectedPiece;
348 this.selectedPiece = null;
350 findMatchingMoves: function(endSquare) {
351 // Run through moves list and return the matching set (if promotions...)
353 this.possibleMoves.forEach(function(m) {
354 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
359 play: function(move) {
360 this.$emit('play-move', move);
367 // TODO: styles to see pieces!