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