my-board seems OK. Now TODO: test my-game (with sockets)
[vchess.git] / public / javascripts / components / board.js
CommitLineData
e5dc87e0
BA
1Vue.component('my-board', {
2 // Last move cannot be guessed from here, and is required to highlight squares
fd373b27
BA
3 // vr: object to check moves, print board...
4 props: ["vr","lastMove","mode","orientation","userColor","gameOver"],
e5dc87e0
BA
5 data: function () {
6 return {
81da2786
BA
7 hints: (!localStorage["hints"] ? true : localStorage["hints"] === "1"),
8 bcolor: localStorage["bcolor"] || "lichess", //lichess, chesscom or chesstempo
9 possibleMoves: [], //filled after each valid click/dragstart
10 choices: [], //promotion pieces, or checkered captures... (as moves)
11 selectedPiece: null, //moving piece (or clicked piece)
12 incheck: [],
13 start: {}, //pixels coordinates + id of starting square (click or drag)
e5dc87e0
BA
14 };
15 },
e5dc87e0 16 render(h) {
baba6070
BA
17 if (!this.vr)
18 return;
e5dc87e0 19 const [sizeX,sizeY] = [V.size.x,V.size.y];
81da2786
BA
20 // Precompute hints squares to facilitate rendering
21 let hintSquares = doubleArray(sizeX, sizeY, false);
22 this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
23 // Also precompute in-check squares
24 let incheckSq = doubleArray(sizeX, sizeY, false);
25 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
baba6070 26 const squareWidth = 40; //TODO: compute this
e5dc87e0
BA
27 const choices = h(
28 'div',
29 {
30 attrs: { "id": "choices" },
31 'class': { 'row': true },
32 style: {
33 "display": this.choices.length>0?"block":"none",
34 "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
35 "width": (this.choices.length * squareWidth) + "px",
36 "height": squareWidth + "px",
81da2786 37 },
e5dc87e0
BA
38 },
39 this.choices.map(m => { //a "choice" is a move
40 return h('div',
41 {
42 'class': {
43 'board': true,
44 ['board'+sizeY]: true,
45 },
46 style: {
47 'width': (100/this.choices.length) + "%",
48 'padding-bottom': (100/this.choices.length) + "%",
81da2786 49 },
81da2786 50 },
e5dc87e0 51 [h('img',
81da2786 52 {
e5dc87e0
BA
53 attrs: { "src": '/images/pieces/' +
54 V.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
55 'class': { 'choice-piece': true },
56 on: {
57 "click": e => { this.play(m); this.choices=[]; },
58 // NOTE: add 'touchstart' event to fix a problem on smartphones
59 "touchstart": e => { this.play(m); this.choices=[]; },
81da2786 60 },
81da2786 61 })
e5dc87e0
BA
62 ]
63 );
64 })
65 );
66 // Create board element (+ reserves if needed by variant or mode)
67 const lm = this.lastMove;
68 const showLight = this.hints && variant.name != "Dark";
69 const gameDiv = h(
70 'div',
81da2786 71 {
e5dc87e0
BA
72 'class': {
73 'game': true,
74 'clearer': true,
75 },
76 },
77 [_.range(sizeX).map(i => {
78 let ci = (this.orientation=='w' ? i : sizeX-i-1);
79 return h(
80 'div',
81da2786 81 {
e5dc87e0
BA
82 'class': {
83 'row': true,
84 },
85 style: { 'opacity': this.choices.length>0?"0.5":"1" },
81da2786 86 },
e5dc87e0
BA
87 _.range(sizeY).map(j => {
88 let cj = (this.orientation=='w' ? j : sizeY-j-1);
89 let elems = [];
90 if (this.vr.board[ci][cj] != V.EMPTY && (variant.name!="Dark"
baba6070
BA
91 || this.gameOver || this.mode == "analyze"
92 || this.vr.enlightened[this.userColor][ci][cj]))
81da2786 93 {
e5dc87e0
BA
94 elems.push(
95 h(
96 'img',
97 {
98 'class': {
99 'piece': true,
100 'ghost': !!this.selectedPiece
101 && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
102 },
103 attrs: {
104 src: "/images/pieces/" +
105 V.getPpath(this.vr.board[ci][cj]) + ".svg",
106 },
107 }
108 )
109 );
110 }
111 if (this.hints && hintSquares[ci][cj])
81da2786 112 {
e5dc87e0
BA
113 elems.push(
114 h(
115 'img',
116 {
117 'class': {
118 'mark-square': true,
119 },
120 attrs: {
121 src: "/images/mark.svg",
122 },
123 }
124 )
125 );
126 }
127 return h(
128 'div',
81da2786
BA
129 {
130 'class': {
e5dc87e0
BA
131 'board': true,
132 ['board'+sizeY]: true,
133 'light-square': (i+j)%2==0,
134 'dark-square': (i+j)%2==1,
135 [this.bcolor]: true,
136 'in-shadow': variant.name=="Dark" && !this.gameOver
baba6070 137 && this.mode != "analyze"
e5dc87e0
BA
138 && !this.vr.enlightened[this.userColor][ci][cj],
139 'highlight': showLight && !!lm && _.isMatch(lm.end, {x:ci,y:cj}),
140 'incheck': showLight && incheckSq[ci][cj],
141 },
142 attrs: {
143 id: this.getSquareId({x:ci,y:cj}),
81da2786
BA
144 },
145 },
e5dc87e0
BA
146 elems
147 );
148 })
81da2786 149 );
e5dc87e0
BA
150 }), choices]
151 );
152 let elementArray = [choices, gameDiv];
153 if (!!this.vr.reserve)
154 {
155 const shiftIdx = (this.userColor=="w" ? 0 : 1);
156 let myReservePiecesArray = [];
157 for (let i=0; i<V.RESERVE_PIECES.length; i++)
158 {
159 myReservePiecesArray.push(h('div',
160 {
161 'class': {'board':true, ['board'+sizeY]:true},
162 attrs: { id: this.getSquareId({x:sizeX+shiftIdx,y:i}) }
163 },
164 [
165 h('img',
166 {
167 'class': {"piece":true, "reserve":true},
168 attrs: {
169 "src": "/images/pieces/" +
170 this.vr.getReservePpath(this.userColor,i) + ".svg",
171 }
172 }),
173 h('sup',
174 {"class": { "reserve-count": true } },
175 [ this.vr.reserve[this.userColor][V.RESERVE_PIECES[i]] ]
176 )
177 ]));
178 }
179 let oppReservePiecesArray = [];
fd373b27 180 const oppCol = V.GetOppCol(this.userColor);
e5dc87e0
BA
181 for (let i=0; i<V.RESERVE_PIECES.length; i++)
182 {
183 oppReservePiecesArray.push(h('div',
184 {
185 'class': {'board':true, ['board'+sizeY]:true},
186 attrs: { id: this.getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
187 },
188 [
189 h('img',
190 {
191 'class': {"piece":true, "reserve":true},
192 attrs: {
193 "src": "/images/pieces/" +
194 this.vr.getReservePpath(oppCol,i) + ".svg",
195 }
196 }),
197 h('sup',
198 {"class": { "reserve-count": true } },
199 [ this.vr.reserve[oppCol][V.RESERVE_PIECES[i]] ]
200 )
201 ]));
81da2786 202 }
e5dc87e0
BA
203 let reserves = h('div',
204 {
205 'class':{
206 'game': true,
207 "reserve-div": true,
208 },
209 },
210 [
81da2786
BA
211 h('div',
212 {
e5dc87e0
BA
213 'class': {
214 'row': true,
215 "reserve-row-1": true,
216 },
81da2786 217 },
e5dc87e0
BA
218 myReservePiecesArray
219 ),
220 h('div',
221 { 'class': { 'row': true }},
222 oppReservePiecesArray
81da2786 223 )
e5dc87e0
BA
224 ]
225 );
226 elementArray.push(reserves);
227 }
228 return h(
229 'div',
230 {
231 'class': {
232 "col-sm-12":true,
233 "col-md-10":true,
234 "col-md-offset-1":true,
235 "col-lg-8":true,
236 "col-lg-offset-2":true,
237 },
238 // NOTE: click = mousedown + mouseup
81da2786
BA
239 on: {
240 mousedown: this.mousedown,
241 mousemove: this.mousemove,
242 mouseup: this.mouseup,
243 touchstart: this.mousedown,
244 touchmove: this.mousemove,
245 touchend: this.mouseup,
246 },
e5dc87e0
BA
247 },
248 elementArray
249 );
250 },
251 methods: {
252 // Get the identifier of a HTML square from its numeric coordinates o.x,o.y.
81da2786
BA
253 getSquareId: function(o) {
254 // NOTE: a separator is required to allow any size of board
255 return "sq-" + o.x + "-" + o.y;
256 },
257 // Inverse function
258 getSquareFromId: function(id) {
259 let idParts = id.split('-');
260 return [parseInt(idParts[1]), parseInt(idParts[2])];
261 },
262 mousedown: function(e) {
263 e = e || window.event;
264 let ingame = false;
265 let elem = e.target;
266 while (!ingame && elem !== null)
267 {
268 if (elem.classList.contains("game"))
269 {
270 ingame = true;
271 break;
272 }
273 elem = elem.parentElement;
274 }
275 if (!ingame) //let default behavior (click on button...)
276 return;
277 e.preventDefault(); //disable native drag & drop
278 if (!this.selectedPiece && e.target.classList.contains("piece"))
279 {
280 // Next few lines to center the piece on mouse cursor
281 let rect = e.target.parentNode.getBoundingClientRect();
282 this.start = {
283 x: rect.x + rect.width/2,
284 y: rect.y + rect.width/2,
285 id: e.target.parentNode.id
286 };
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 = this.getSquareFromId(e.target.parentNode.id);
293 this.possibleMoves = [];
fd373b27 294 const color = this.mode=="analyze" || this.gameOver
e5dc87e0
BA
295 ? this.vr.turn
296 : this.userColor;
297 if (this.vr.canIplay(color,startSquare))
298 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
81da2786
BA
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 = this.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 },
fd373b27
BA
359 play: function(move) {
360 this.$emit('play-move', move);
e5dc87e0
BA
361 },
362 },
363})