Separate client and server codes. Keep everything in one git repo for simplicity
[vchess.git] / client / client_OLD / javascripts / components / board.js
CommitLineData
a3ab5fdb
BA
1// This can work for squared boards (2 or 4 players), with some adaptations (TODO)
2// TODO: for 3 players, write a "board3.js"
e5dc87e0
BA
3Vue.component('my-board', {
4 // Last move cannot be guessed from here, and is required to highlight squares
fd373b27 5 // vr: object to check moves, print board...
81bc1102
BA
6 // mode: HH, HC or analyze
7 // userColor: for mode HH or HC
8 props: ["vr","lastMove","mode","orientation","userColor"],
e5dc87e0
BA
9 data: function () {
10 return {
81da2786
BA
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)
e5dc87e0
BA
18 };
19 },
e5dc87e0 20 render(h) {
baba6070
BA
21 if (!this.vr)
22 return;
e5dc87e0 23 const [sizeX,sizeY] = [V.size.x,V.size.y];
81da2786
BA
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; });
baba6070 30 const squareWidth = 40; //TODO: compute this
e5dc87e0
BA
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",
81da2786 41 },
e5dc87e0
BA
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) + "%",
81da2786 53 },
81da2786 54 },
e5dc87e0 55 [h('img',
81da2786 56 {
e5dc87e0
BA
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=[]; },
81da2786 64 },
81da2786 65 })
e5dc87e0
BA
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',
81da2786 75 {
e5dc87e0
BA
76 'class': {
77 'game': true,
78 'clearer': true,
79 },
80 },
81 [_.range(sizeX).map(i => {
82 let ci = (this.orientation=='w' ? i : sizeX-i-1);
83 return h(
84 'div',
81da2786 85 {
e5dc87e0
BA
86 'class': {
87 'row': true,
88 },
89 style: { 'opacity': this.choices.length>0?"0.5":"1" },
81da2786 90 },
e5dc87e0
BA
91 _.range(sizeY).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"
baba6070
BA
95 || this.gameOver || this.mode == "analyze"
96 || this.vr.enlightened[this.userColor][ci][cj]))
81da2786 97 {
e5dc87e0
BA
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])
81da2786 116 {
e5dc87e0
BA
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',
81da2786
BA
133 {
134 'class': {
e5dc87e0
BA
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
baba6070 141 && this.mode != "analyze"
e5dc87e0
BA
142 && !this.vr.enlightened[this.userColor][ci][cj],
143 'highlight': showLight && !!lm && _.isMatch(lm.end, {x:ci,y:cj}),
144 'incheck': showLight && incheckSq[ci][cj],
145 },
146 attrs: {
582df349 147 id: getSquareId({x:ci,y:cj}),
81da2786
BA
148 },
149 },
e5dc87e0
BA
150 elems
151 );
152 })
81da2786 153 );
e5dc87e0
BA
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},
582df349 166 attrs: { id: getSquareId({x:sizeX+shiftIdx,y:i}) }
e5dc87e0
BA
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 = [];
fd373b27 184 const oppCol = V.GetOppCol(this.userColor);
e5dc87e0
BA
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},
582df349 190 attrs: { id: getSquareId({x:sizeX+(1-shiftIdx),y:i}) }
e5dc87e0
BA
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 ]));
81da2786 206 }
e5dc87e0
BA
207 let reserves = h('div',
208 {
209 'class':{
210 'game': true,
211 "reserve-div": true,
212 },
213 },
214 [
81da2786
BA
215 h('div',
216 {
e5dc87e0
BA
217 'class': {
218 'row': true,
219 "reserve-row-1": true,
220 },
81da2786 221 },
e5dc87e0
BA
222 myReservePiecesArray
223 ),
224 h('div',
225 { 'class': { 'row': true }},
226 oppReservePiecesArray
81da2786 227 )
e5dc87e0
BA
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
81da2786
BA
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 },
e5dc87e0
BA
251 },
252 elementArray
253 );
254 },
255 methods: {
81da2786
BA
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;
582df349 286 const startSquare = getSquareFromId(e.target.parentNode.id);
81da2786 287 this.possibleMoves = [];
fd373b27 288 const color = this.mode=="analyze" || this.gameOver
e5dc87e0
BA
289 ? this.vr.turn
290 : this.userColor;
291 if (this.vr.canIplay(color,startSquare))
292 this.possibleMoves = this.vr.getPossibleMovesFrom(startSquare);
81da2786
BA
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
582df349 332 let endSquare = getSquareFromId(landing.id);
81da2786
BA
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 },
fd373b27
BA
353 play: function(move) {
354 this.$emit('play-move', move);
e5dc87e0
BA
355 },
356 },
357})