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