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