Fix switching chess
[vchess.git] / public / javascripts / components / game.js
CommitLineData
1d184b4c
BA
1Vue.component('my-game', {
2 data: function() {
3 return {
4 vr: null, //object to check moves, store them, FEN..
5 mycolor: "w",
6 possibleMoves: [], //filled after each valid click/dragstart
7 choices: [], //promotion pieces, or checkered captures... (contain possible pieces)
8 start: {}, //pixels coordinates + id of starting square (click or drag)
9 selectedPiece: null, //moving piece (or clicked piece)
10 conn: null, //socket messages
dfb4afc1 11 score: "*", //'*' means 'unfinished'
1d184b4c
BA
12 mode: "idle", //human, computer or idle (when not playing)
13 oppid: "", //opponent ID in case of HH game
14 oppConnected: false,
186516b8 15 seek: false,
762b7c9c 16 fenStart: "",
4b5fe306 17 incheck: [],
3840e240 18 pgnTxt: "",
3ed62725 19 expert: document.cookie.length>0 ? document.cookie.substr(-1)=="1" : false,
efb20746 20 gameId: "", //used to limit computer moves' time
1d184b4c
BA
21 };
22 },
23 render(h) {
c94bc812 24 const [sizeX,sizeY] = VariantRules.size;
1d184b4c
BA
25 // Precompute hints squares to facilitate rendering
26 let hintSquares = doubleArray(sizeX, sizeY, false);
27 this.possibleMoves.forEach(m => { hintSquares[m.end.x][m.end.y] = true; });
4b5fe306
BA
28 // Also precompute in-check squares
29 let incheckSq = doubleArray(sizeX, sizeY, false);
30 this.incheck.forEach(sq => { incheckSq[sq[0]][sq[1]] = true; });
1d184b4c 31 let elementArray = [];
186516b8
BA
32 const playingHuman = (this.mode == "human");
33 const playingComp = (this.mode == "computer");
1d184b4c
BA
34 let actionArray = [
35 h('button',
36 {
f3802fcd 37 on: { click: this.clickGameSeek },
1d184b4c 38 attrs: { "aria-label": 'New game VS human' },
186516b8
BA
39 'class': {
40 "tooltip": true,
0706ea91 41 "bottom": true, //display below
186516b8
BA
42 "seek": this.seek,
43 "playing": playingHuman,
44 },
1d184b4c
BA
45 },
46 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
47 h('button',
48 {
f3802fcd 49 on: { click: this.clickComputerGame },
1d184b4c 50 attrs: { "aria-label": 'New game VS computer' },
186516b8
BA
51 'class': {
52 "tooltip":true,
0706ea91 53 "bottom": true,
186516b8
BA
54 "playing": playingComp,
55 },
1d184b4c
BA
56 },
57 [h('i', { 'class': { "material-icons": true } }, "computer")])
58 ];
59 if (!!this.vr)
60 {
bdb1f12d
BA
61 const square00 = document.getElementById("sq-0-0");
62 const squareWidth = !!square00
63 ? parseFloat(window.getComputedStyle(square00).width.slice(0,-2))
64 : 0;
65 const indicWidth = (squareWidth>0 ? squareWidth/2 : 20);
1d184b4c
BA
66 if (this.mode == "human")
67 {
68 let connectedIndic = h(
69 'div',
70 {
71 "class": {
bdb1f12d
BA
72 "topindicator": true,
73 "indic-left": true,
1d184b4c
BA
74 "connected": this.oppConnected,
75 "disconnected": !this.oppConnected,
76 },
bdb1f12d
BA
77 style: {
78 "width": indicWidth + "px",
79 "height": indicWidth + "px",
80 },
1d184b4c
BA
81 }
82 );
83 elementArray.push(connectedIndic);
84 }
bdb1f12d
BA
85 let turnIndic = h(
86 'div',
87 {
88 "class": {
89 "topindicator": true,
90 "indic-right": true,
91 "white-turn": this.vr.turn=="w",
92 "black-turn": this.vr.turn=="b",
93 },
94 style: {
95 "width": indicWidth + "px",
96 "height": indicWidth + "px",
97 },
98 }
99 );
100 elementArray.push(turnIndic);
3ed62725
BA
101 let expertSwitch = h(
102 'button',
103 {
104 on: { click: this.toggleExpertMode },
105 attrs: { "aria-label": 'Toggle expert mode' },
106 'class': {
107 "tooltip":true,
108 "topindicator": true,
109 "indic-right": true,
110 "expert-switch": true,
111 "expert-mode": this.expert,
112 },
113 },
114 [h('i', { 'class': { "material-icons": true } }, "remove_red_eye")]
115 );
116 elementArray.push(expertSwitch);
1d184b4c
BA
117 let choices = h('div',
118 {
119 attrs: { "id": "choices" },
120 'class': { 'row': true },
121 style: {
1d184b4c
BA
122 "display": this.choices.length>0?"block":"none",
123 "top": "-" + ((sizeY/2)*squareWidth+squareWidth/2) + "px",
124 "width": (this.choices.length * squareWidth) + "px",
125 "height": squareWidth + "px",
126 },
127 },
128 this.choices.map( m => { //a "choice" is a move
129 return h('div',
130 {
c94bc812
BA
131 'class': {
132 'board': true,
8a196305 133 ['board'+sizeY]: true,
c94bc812 134 },
1d184b4c
BA
135 style: {
136 'width': (100/this.choices.length) + "%",
137 'padding-bottom': (100/this.choices.length) + "%",
138 },
139 },
140 [h('img',
141 {
4b353936
BA
142 attrs: { "src": '/images/pieces/' +
143 VariantRules.getPpath(m.appear[0].c+m.appear[0].p) + '.svg' },
c94bc812 144 'class': { 'choice-piece': true },
1d184b4c
BA
145 on: { "click": e => { this.play(m); this.choices=[]; } },
146 })
147 ]
148 );
149 })
150 );
151 // Create board element (+ reserves if needed by variant or mode)
152 let gameDiv = h('div',
153 {
154 'class': { 'game': true },
155 },
156 [_.range(sizeX).map(i => {
157 let ci = this.mycolor=='w' ? i : sizeX-i-1;
158 return h(
159 'div',
160 {
161 'class': {
162 'row': true,
163 },
164 style: { 'opacity': this.choices.length>0?"0.5":"1" },
165 },
166 _.range(sizeY).map(j => {
167 let cj = this.mycolor=='w' ? j : sizeY-j-1;
168 let elems = [];
169 if (this.vr.board[ci][cj] != VariantRules.EMPTY)
170 {
171 elems.push(
172 h(
173 'img',
174 {
175 'class': {
176 'piece': true,
4b353936
BA
177 'ghost': !!this.selectedPiece
178 && this.selectedPiece.parentNode.id == "sq-"+ci+"-"+cj,
1d184b4c
BA
179 },
180 attrs: {
4b353936
BA
181 src: "/images/pieces/" +
182 VariantRules.getPpath(this.vr.board[ci][cj]) + ".svg",
1d184b4c
BA
183 },
184 }
185 )
186 );
187 }
3ed62725 188 if (!this.expert && hintSquares[ci][cj])
1d184b4c
BA
189 {
190 elems.push(
191 h(
192 'img',
193 {
194 'class': {
195 'mark-square': true,
196 },
197 attrs: {
198 src: "/images/mark.svg",
199 },
200 }
201 )
202 );
203 }
30ff6e04 204 const lm = this.vr.lastMove;
e64a4eff 205 const highlight = !!lm && _.isMatch(lm.end, {x:ci,y:cj});
1d184b4c
BA
206 return h(
207 'div',
208 {
209 'class': {
210 'board': true,
8a196305 211 ['board'+sizeY]: true,
3ed62725
BA
212 'light-square': (i+j)%2==0 && (this.expert || !highlight),
213 'dark-square': (i+j)%2==1 && (this.expert || !highlight),
214 'highlight': !this.expert && highlight,
215 'incheck': !this.expert && incheckSq[ci][cj],
1d184b4c
BA
216 },
217 attrs: {
218 id: this.getSquareId({x:ci,y:cj}),
219 },
220 },
221 elems
222 );
223 })
224 );
225 }), choices]
226 );
204e289b
BA
227 if (this.mode != "idle")
228 {
229 actionArray.push(
230 h('button',
231 {
232 on: { click: this.resign },
233 attrs: { "aria-label": 'Resign' },
234 'class': {
235 "tooltip":true,
236 "bottom": true,
237 },
0706ea91 238 },
204e289b
BA
239 [h('i', { 'class': { "material-icons": true } }, "flag")])
240 );
241 }
1d184b4c 242 elementArray.push(gameDiv);
1221ac47
BA
243 if (!!this.vr.reserve) //TODO: table, show counts for reserve pieces
244 //<tr style="padding:0">
245 // <td style="padding:0;font-size:10px">3</td>
246 {
247 let reservePiecesArray = [];
248 for (let i=0; i<VariantRules.RESERVE_PIECES.length; i++)
249 {
250 reservePiecesArray.push(h('img',
251 {
252 'class': {"piece":true},
253 attrs: {
254 "src": "/images/pieces/" +
255 this.vr.getReservePpath(this.mycolor,i) + ".svg",
256 id: this.getSquareId({x:sizeX,y:i}),
257 }
258 })
259 );
260 }
261 let reserve = h('div',
262 {'class':{'game':true}}, [
263 h('div',
264 { 'class': { 'row': true }},
265 [
266 h('div',
267 {'class':{'board':true, ['board'+sizeY]:true}},
268 reservePiecesArray
269 )
270 ]
271 )
272 ],
273 );
274 elementArray.push(reserve);
275 }
f3802fcd 276 const eogMessage = this.getEndgameMessage(this.score);
1d184b4c
BA
277 const modalEog = [
278 h('input',
279 {
ecf44502 280 attrs: { "id": "modal-eog", type: "checkbox" },
1d184b4c
BA
281 "class": { "modal": true },
282 }),
283 h('div',
284 {
285 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
286 },
287 [
288 h('div',
289 {
290 "class": { "card": true, "smallpad": true },
291 },
01a135e2
BA
292 [
293 h('label',
294 {
295 attrs: { "for": "modal-eog" },
296 "class": { "modal-close": true },
297 }
298 ),
299 h('h3',
300 {
301 "class": { "section": true },
302 domProps: { innerHTML: eogMessage },
303 }
304 )
305 ]
1d184b4c
BA
306 )
307 ]
308 )
309 ];
310 elementArray = elementArray.concat(modalEog);
311 }
312 const modalNewgame = [
313 h('input',
314 {
ecf44502 315 attrs: { "id": "modal-newgame", type: "checkbox" },
1d184b4c
BA
316 "class": { "modal": true },
317 }),
318 h('div',
319 {
320 attrs: { "role": "dialog", "aria-labelledby": "dialog-title" },
321 },
322 [
323 h('div',
324 {
325 "class": { "card": true, "smallpad": true },
326 },
327 [
328 h('label',
329 {
ecf44502 330 attrs: { "id": "close-newgame", "for": "modal-newgame" },
1d184b4c
BA
331 "class": { "modal-close": true },
332 }
333 ),
334 h('h3',
335 {
336 "class": { "section": true },
337 domProps: { innerHTML: "New game" },
338 }
339 ),
340 h('p',
341 {
342 "class": { "section": true },
343 domProps: { innerHTML: "Waiting for opponent..." },
344 }
345 )
346 ]
347 )
348 ]
349 )
350 ];
351 elementArray = elementArray.concat(modalNewgame);
352 const actions = h('div',
353 {
354 attrs: { "id": "actions" },
355 'class': { 'text-center': true },
356 },
357 actionArray
358 );
359 elementArray.push(actions);
01a135e2
BA
360 if (this.score != "*")
361 {
362 elementArray.push(
363 h('div',
01ca2adc 364 { attrs: { id: "pgn-div" } },
01a135e2 365 [
01ca2adc
BA
366 h('a',
367 {
368 attrs: {
369 id: "download",
370 href: "#",
371 }
372 }
373 ),
01a135e2
BA
374 h('p',
375 {
01ca2adc
BA
376 attrs: { id: "pgn-game" },
377 on: { click: this.download },
01a135e2 378 domProps: {
3840e240 379 innerHTML: this.pgnTxt
01a135e2
BA
380 }
381 }
382 )
383 ]
384 )
385 );
386 }
1d184b4c
BA
387 return h(
388 'div',
389 {
390 'class': {
391 "col-sm-12":true,
392 "col-md-8":true,
393 "col-md-offset-2":true,
394 "col-lg-6":true,
395 "col-lg-offset-3":true,
396 },
397 // NOTE: click = mousedown + mouseup --> what about smartphone?!
398 on: {
399 mousedown: this.mousedown,
400 mousemove: this.mousemove,
401 mouseup: this.mouseup,
402 touchdown: this.mousedown,
403 touchmove: this.mousemove,
404 touchup: this.mouseup,
405 },
406 },
407 elementArray
408 );
409 },
410 created: function() {
411 const url = socketUrl;
412 const continuation = (localStorage.getItem("variant") === variant);
413 this.myid = continuation
414 ? localStorage.getItem("myid")
415 // random enough (TODO: function)
416 : (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
92ff5bae
BA
417 if (!continuation)
418 {
419 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
420 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err => {});
421 }
1d184b4c 422 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
d35f20e4 423 const socketOpenListener = () => {
1d184b4c
BA
424 if (continuation)
425 {
dfb4afc1
BA
426 const fen = localStorage.getItem("fen");
427 const mycolor = localStorage.getItem("mycolor");
428 const oppid = localStorage.getItem("oppid");
429 const moves = JSON.parse(localStorage.getItem("moves"));
430 this.newGame("human", fen, mycolor, oppid, moves, true);
a29d9d6b 431 // Send ping to server (answer pong if opponent is connected)
ecf44502 432 this.conn.send(JSON.stringify({code:"ping",oppid:this.oppid}));
1d184b4c 433 }
30ff6e04
BA
434 else if (localStorage.getItem("newgame") === variant)
435 {
436 // New game request has been cancelled on disconnect
186516b8 437 this.seek = true;
001344b9 438 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
30ff6e04 439 }
1d184b4c 440 };
d35f20e4 441 const socketMessageListener = msg => {
1d184b4c
BA
442 const data = JSON.parse(msg.data);
443 switch (data.code)
444 {
445 case "newgame": //opponent found
446 this.newGame("human", data.fen, data.color, data.oppid); //oppid: opponent socket ID
447 break;
448 case "newmove": //..he played!
449 this.play(data.move, "animate");
450 break;
f3802fcd 451 case "pong": //received if we sent a ping (game still alive on our side)
1d184b4c 452 this.oppConnected = true;
a29d9d6b 453 const L = this.vr.moves.length;
f3802fcd 454 // Send our "last state" informations to opponent
a29d9d6b
BA
455 this.conn.send(JSON.stringify({
456 code:"lastate",
f3802fcd 457 oppid:this.oppid,
a29d9d6b
BA
458 lastMove:L>0?this.vr.moves[L-1]:undefined,
459 movesCount:L,
460 }));
1d184b4c 461 break;
a29d9d6b
BA
462 case "lastate": //got opponent infos about last move (we might have resigned)
463 if (this.mode!="human" || this.oppid!=data.oppid)
464 {
465 // OK, we resigned
466 this.conn.send(JSON.stringify({
467 code:"lastate",
f3802fcd 468 oppid:this.oppid,
a29d9d6b
BA
469 lastMove:undefined,
470 movesCount:-1,
471 }));
472 }
473 else if (data.movesCount < 0)
474 {
475 // OK, he resigned
476 this.endGame(this.mycolor=="w"?"1-0":"0-1");
477 }
478 else if (data.movesCount < this.vr.moves.length)
479 {
480 // We must tell last move to opponent
481 const L = this.vr.moves.length;
482 this.conn.send(JSON.stringify({
483 code:"lastate",
f3802fcd 484 oppid:this.oppid,
a29d9d6b
BA
485 lastMove:this.vr.moves[L-1],
486 movesCount:L,
487 }));
488 }
489 else if (data.movesCount > this.vr.moves.length) //just got last move from him
490 this.play(data.lastMove, "animate");
ecf44502 491 break;
1d184b4c 492 case "resign": //..you won!
dfb4afc1 493 this.endGame(this.mycolor=="w"?"1-0":"0-1");
1d184b4c 494 break;
f3802fcd 495 // TODO: also use (dis)connect info to count online players?
1d184b4c
BA
496 case "connect":
497 case "disconnect":
498 if (this.mode == "human" && this.oppid == data.id)
499 this.oppConnected = (data.code == "connect");
500 break;
501 }
502 };
d35f20e4 503 const socketCloseListener = () => {
d35f20e4
BA
504 this.conn = new WebSocket(url + "/?sid=" + this.myid + "&page=" + variant);
505 this.conn.addEventListener('open', socketOpenListener);
506 this.conn.addEventListener('message', socketMessageListener);
507 this.conn.addEventListener('close', socketCloseListener);
508 };
509 this.conn.onopen = socketOpenListener;
510 this.conn.onmessage = socketMessageListener;
511 this.conn.onclose = socketCloseListener;
1d184b4c
BA
512 },
513 methods: {
01ca2adc
BA
514 download: function() {
515 let content = document.getElementById("pgn-game").innerHTML;
516 content = content.replace(/<br>/g, "\n");
517 // Prepare and trigger download link
518 let downloadAnchor = document.getElementById("download");
519 downloadAnchor.setAttribute("download", "game.pgn");
520 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
521 downloadAnchor.click();
522 },
dfb4afc1
BA
523 endGame: function(score) {
524 this.score = score;
ecf44502 525 let modalBox = document.getElementById("modal-eog");
186516b8 526 modalBox.checked = true;
204e289b 527 // Variants may have special PGN structure (so next function isn't defined here)
3840e240
BA
528 this.pgnTxt = this.vr.getPGN(this.mycolor, this.score, this.fenStart, this.mode);
529 setTimeout(() => { modalBox.checked = false; }, 2000);
1d184b4c
BA
530 if (this.mode == "human")
531 this.clearStorage();
3840e240 532 this.mode = "idle";
1d184b4c
BA
533 this.oppid = "";
534 },
f3802fcd
BA
535 getEndgameMessage: function(score) {
536 let eogMessage = "Unfinished";
537 switch (this.score)
538 {
539 case "1-0":
540 eogMessage = "White win";
541 break;
542 case "0-1":
543 eogMessage = "Black win";
544 break;
545 case "1/2":
546 eogMessage = "Draw";
547 break;
548 }
549 return eogMessage;
550 },
3ed62725
BA
551 toggleExpertMode: function() {
552 this.expert = !this.expert;
553 document.cookie = "expert=" + (this.expert ? "1" : "0");
554 },
1d184b4c
BA
555 resign: function() {
556 if (this.mode == "human" && this.oppConnected)
d35f20e4
BA
557 {
558 try {
559 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
560 } catch (INVALID_STATE_ERR) {
a29d9d6b 561 return; //socket is not ready (and not yet reconnected)
d35f20e4
BA
562 }
563 }
dfb4afc1 564 this.endGame(this.mycolor=="w"?"0-1":"1-0");
1d184b4c 565 },
762b7c9c
BA
566 setStorage: function() {
567 localStorage.setItem("myid", this.myid);
568 localStorage.setItem("variant", variant);
569 localStorage.setItem("mycolor", this.mycolor);
570 localStorage.setItem("oppid", this.oppid);
571 localStorage.setItem("fenStart", this.fenStart);
572 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
1d184b4c 573 localStorage.setItem("fen", this.vr.getFen());
762b7c9c
BA
574 },
575 updateStorage: function() {
dfb4afc1 576 localStorage.setItem("moves", JSON.stringify(this.vr.moves));
762b7c9c 577 localStorage.setItem("fen", this.vr.getFen());
1d184b4c
BA
578 },
579 clearStorage: function() {
580 delete localStorage["variant"];
581 delete localStorage["myid"];
582 delete localStorage["mycolor"];
583 delete localStorage["oppid"];
762b7c9c 584 delete localStorage["fenStart"];
1d184b4c 585 delete localStorage["fen"];
dfb4afc1 586 delete localStorage["moves"];
1d184b4c 587 },
f3802fcd
BA
588 clickGameSeek: function() {
589 if (this.mode == "human")
590 return; //no newgame while playing
591 if (this.seek)
01a135e2 592 {
f3802fcd 593 delete localStorage["newgame"]; //cancel game seek
01a135e2
BA
594 this.seek = false;
595 }
f3802fcd 596 else
f3802fcd 597 this.newGame("human");
f3802fcd
BA
598 },
599 clickComputerGame: function() {
600 if (this.mode == "human")
601 return; //no newgame while playing
602 this.newGame("computer");
603 },
dfb4afc1 604 newGame: function(mode, fenInit, color, oppId, moves, continuation) {
55eb331d 605 const fen = fenInit || VariantRules.GenRandInitFen();
1d184b4c 606 console.log(fen); //DEBUG
dfb4afc1 607 this.score = "*";
1d184b4c
BA
608 if (mode=="human" && !oppId)
609 {
cd3174c5
BA
610 const storageVariant = localStorage.getItem("variant");
611 if (!!storageVariant && storageVariant !== variant)
612 {
cd3174c5
BA
613 alert("Finish your " + storageVariant + " game first!");
614 return;
615 }
1d184b4c 616 // Send game request and wait..
01a135e2
BA
617 localStorage["newgame"] = variant;
618 this.seek = true;
1d184b4c 619 this.clearStorage(); //in case of
d35f20e4
BA
620 try {
621 this.conn.send(JSON.stringify({code:"newgame", fen:fen}));
622 } catch (INVALID_STATE_ERR) {
623 return; //nothing achieved
624 }
f3802fcd 625 if (continuation !== "reconnect") //TODO: bad HACK...
a68d899d 626 {
ecf44502 627 let modalBox = document.getElementById("modal-newgame");
a68d899d
BA
628 modalBox.checked = true;
629 setTimeout(() => { modalBox.checked = false; }, 2000);
630 }
1d184b4c
BA
631 return;
632 }
efb20746
BA
633 // random enough (TODO: function)
634 this.gameId = (Date.now().toString(36) + Math.random().toString(36).substr(2, 7)).toUpperCase();
dfb4afc1 635 this.vr = new VariantRules(fen, moves || []);
3840e240 636 this.pgnTxt = ""; //redundant with this.score = "*", but cleaner
1d184b4c 637 this.mode = mode;
1fcaa356 638 this.incheck = []; //in case of
762b7c9c
BA
639 this.fenStart = continuation
640 ? localStorage.getItem("fenStart")
641 : fen.split(" ")[0]; //Only the position matters
1d184b4c
BA
642 if (mode=="human")
643 {
644 // Opponent found!
645 if (!continuation)
646 {
ecf44502 647 // Not playing sound on game continuation:
ea8417ff 648 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err => {});
ecf44502 649 document.getElementById("modal-newgame").checked = false;
1d184b4c
BA
650 }
651 this.oppid = oppId;
652 this.oppConnected = true;
653 this.mycolor = color;
186516b8 654 this.seek = false;
e64a4eff
BA
655 if (!!moves && moves.length > 0) //imply continuation
656 {
e64a4eff 657 const lastMove = moves[moves.length-1];
cd4cad04 658 this.vr.undo(lastMove);
46302e64 659 this.incheck = this.vr.getCheckSquares(lastMove);
e64a4eff
BA
660 this.vr.play(lastMove, "ingame");
661 }
186516b8 662 delete localStorage["newgame"];
762b7c9c 663 this.setStorage(); //in case of interruptions
1d184b4c
BA
664 }
665 else //against computer
666 {
f3c10e18 667 this.mycolor = Math.random() < 0.5 ? 'w' : 'b';
1d184b4c
BA
668 if (this.mycolor == 'b')
669 setTimeout(this.playComputerMove, 500);
670 }
671 },
672 playComputerMove: function() {
4b353936 673 const timeStart = Date.now();
3c09dc49 674 const nbMoves = this.vr.moves.length; //using played moves to know if search finished
efb20746 675 const gameId = this.gameId; //to know if game was reset before timer end
3c09dc49
BA
676 setTimeout(
677 () => {
efb20746
BA
678 if (gameId != this.gameId)
679 return; //game stopped
3c09dc49
BA
680 const L = this.vr.moves.length;
681 if (nbMoves == L || !this.vr.moves[L-1].notation) //move search didn't finish
682 this.vr.shouldReturn = true;
683 }, 5000);
46302e64 684 const compMove = this.vr.getComputerMove();
4b353936
BA
685 // (first move) HACK: avoid selecting elements before they appear on page:
686 const delay = Math.max(500-(Date.now()-timeStart), 0);
687 setTimeout(() => this.play(compMove, "animate"), delay);
1d184b4c
BA
688 },
689 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
690 getSquareId: function(o) {
691 // NOTE: a separator is required to allow any size of board
692 return "sq-" + o.x + "-" + o.y;
693 },
694 // Inverse function
695 getSquareFromId: function(id) {
696 let idParts = id.split('-');
697 return [parseInt(idParts[1]), parseInt(idParts[2])];
698 },
699 mousedown: function(e) {
700 e = e || window.event;
701 e.preventDefault(); //disable native drag & drop
702 if (!this.selectedPiece && e.target.classList.contains("piece"))
703 {
704 // Next few lines to center the piece on mouse cursor
705 let rect = e.target.parentNode.getBoundingClientRect();
706 this.start = {
707 x: rect.x + rect.width/2,
708 y: rect.y + rect.width/2,
709 id: e.target.parentNode.id
710 };
711 this.selectedPiece = e.target.cloneNode();
712 this.selectedPiece.style.position = "absolute";
713 this.selectedPiece.style.top = 0;
714 this.selectedPiece.style.display = "inline-block";
715 this.selectedPiece.style.zIndex = 3000;
716 let startSquare = this.getSquareFromId(e.target.parentNode.id);
55eb331d 717 this.possibleMoves = this.mode!="idle" && this.vr.canIplay(this.mycolor,startSquare)
1d184b4c
BA
718 ? this.vr.getPossibleMovesFrom(startSquare)
719 : [];
720 e.target.parentNode.appendChild(this.selectedPiece);
721 }
722 },
723 mousemove: function(e) {
724 if (!this.selectedPiece)
725 return;
726 e = e || window.event;
727 // If there is an active element, move it around
728 if (!!this.selectedPiece)
729 {
730 this.selectedPiece.style.left = (e.clientX-this.start.x) + "px";
731 this.selectedPiece.style.top = (e.clientY-this.start.y) + "px";
732 }
733 },
734 mouseup: function(e) {
735 if (!this.selectedPiece)
736 return;
737 e = e || window.event;
738 // Read drop target (or parentElement, parentNode... if type == "img")
739 this.selectedPiece.style.zIndex = -3000; //HACK to find square from final coordinates
740 let landing = document.elementFromPoint(e.clientX, e.clientY);
741 this.selectedPiece.style.zIndex = 3000;
742 while (landing.tagName == "IMG") //classList.contains(piece) fails because of mark/highlight
743 landing = landing.parentNode;
744 if (this.start.id == landing.id) //a click: selectedPiece and possibleMoves already filled
745 return;
746 // OK: process move attempt
747 let endSquare = this.getSquareFromId(landing.id);
748 let moves = this.findMatchingMoves(endSquare);
749 this.possibleMoves = [];
750 if (moves.length > 1)
751 this.choices = moves;
752 else if (moves.length==1)
753 this.play(moves[0]);
754 // Else: impossible move
755 this.selectedPiece.parentNode.removeChild(this.selectedPiece);
756 delete this.selectedPiece;
757 this.selectedPiece = null;
758 },
759 findMatchingMoves: function(endSquare) {
760 // Run through moves list and return the matching set (if promotions...)
761 let moves = [];
762 this.possibleMoves.forEach(function(m) {
763 if (endSquare[0] == m.end.x && endSquare[1] == m.end.y)
764 moves.push(m);
765 });
766 return moves;
767 },
768 animateMove: function(move) {
769 let startSquare = document.getElementById(this.getSquareId(move.start));
770 let endSquare = document.getElementById(this.getSquareId(move.end));
771 let rectStart = startSquare.getBoundingClientRect();
772 let rectEnd = endSquare.getBoundingClientRect();
773 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
92ff5bae
BA
774 let movingPiece =
775 document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
776 // HACK for animation (with positive translate, image slides "under background"...)
1d184b4c
BA
777 // Possible improvement: just alter squares on the piece's way...
778 squares = document.getElementsByClassName("board");
779 for (let i=0; i<squares.length; i++)
780 {
781 let square = squares.item(i);
782 if (square.id != this.getSquareId(move.start))
783 square.style.zIndex = "-1";
784 }
785 movingPiece.style.transform = "translate(" + translation.x + "px," + translation.y + "px)";
786 movingPiece.style.transitionDuration = "0.2s";
787 movingPiece.style.zIndex = "3000";
788 setTimeout( () => {
789 for (let i=0; i<squares.length; i++)
790 squares.item(i).style.zIndex = "auto";
791 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
792 this.play(move);
793 }, 200);
794 },
795 play: function(move, programmatic) {
796 if (!!programmatic) //computer or human opponent
797 {
798 this.animateMove(move);
799 return;
800 }
46302e64 801 this.incheck = this.vr.getCheckSquares(move); //is opponent in check?
1d184b4c
BA
802 // Not programmatic, or animation is over
803 if (this.mode == "human" && this.vr.turn == this.mycolor)
a29d9d6b 804 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
ea8417ff 805 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err => {});
1d184b4c
BA
806 this.vr.play(move, "ingame");
807 if (this.mode == "human")
808 this.updateStorage(); //after our moves and opponent moves
46302e64 809 const eog = this.vr.checkGameOver();
1d184b4c
BA
810 if (eog != "*")
811 this.endGame(eog);
812 else if (this.mode == "computer" && this.vr.turn != this.mycolor)
813 setTimeout(this.playComputerMove, 500);
814 },
815 },
816})