1 Vue
.component('my-game', {
4 vr: null, //object to check moves, store them, FEN..
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
19 expert: document
.cookie
.length
>0 ? document
.cookie
.substr(-1)=="1" : false,
20 gameId: "", //used to limit computer moves' time
24 const [sizeX
,sizeY
] = VariantRules
.size
;
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; });
28 // Also precompute in-check squares
29 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
30 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
31 let elementArray
= [];
32 const playingHuman
= (this.mode
== "human");
33 const playingComp
= (this.mode
== "computer");
37 on: { click: this.clickGameSeek
},
38 attrs: { "aria-label": 'New game VS human' },
41 "bottom": true, //display below
43 "playing": playingHuman
,
46 [h('i', { 'class': { "material-icons": true } }, "accessibility")]),
49 on: { click: this.clickComputerGame
},
50 attrs: { "aria-label": 'New game VS computer' },
54 "playing": playingComp
,
57 [h('i', { 'class': { "material-icons": true } }, "computer")])
61 const square00
= document
.getElementById("sq-0-0");
62 const squareWidth
= !!square00
63 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
65 const indicWidth
= (squareWidth
>0 ? squareWidth
/2 : 20);
66 if (this.mode
== "human")
68 let connectedIndic
= h(
74 "connected": this.oppConnected
,
75 "disconnected": !this.oppConnected
,
78 "width": indicWidth
+ "px",
79 "height": indicWidth
+ "px",
83 elementArray
.push(connectedIndic
);
91 "white-turn": this.vr
.turn
=="w",
92 "black-turn": this.vr
.turn
=="b",
95 "width": indicWidth
+ "px",
96 "height": indicWidth
+ "px",
100 elementArray
.push(turnIndic
);
101 let expertSwitch
= h(
104 on: { click: this.toggleExpertMode
},
105 attrs: { "aria-label": 'Toggle expert mode' },
108 "topindicator": true,
110 "expert-switch": true,
111 "expert-mode": this.expert
,
114 [h('i', { 'class': { "material-icons": true } }, "remove_red_eye")]
116 elementArray
.push(expertSwitch
);
117 let choices
= h('div',
119 attrs: { "id": "choices" },
120 'class': { 'row': true },
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",
128 this.choices
.map( m
=> { //a "choice" is a move
133 ['board'+sizeY
]: true,
136 'width': (100/this.choices
.length
) + "%",
137 'padding-bottom': (100/this.choices
.length
) + "%",
142 attrs: { "src": '/images/pieces/' +
143 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
144 'class': { 'choice-piece': true },
145 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
151 // Create board element (+ reserves if needed by variant or mode)
152 let gameDiv
= h('div',
154 'class': { 'game': true },
156 [_
.range(sizeX
).map(i
=> {
157 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
164 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
166 _
.range(sizeY
).map(j
=> {
167 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
169 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
177 'ghost': !!this.selectedPiece
178 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
181 src: "/images/pieces/" +
182 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
188 if (!this.expert
&& hintSquares
[ci
][cj
])
198 src: "/images/mark.svg",
204 const lm
= this.vr
.lastMove
;
205 const showLight
= !this.expert
&&
206 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
212 ['board'+sizeY
]: true,
213 'light-square': (i
+j
)%2==0,
214 'dark-square': (i
+j
)%2==1,
215 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
216 'incheck': showLight
&& incheckSq
[ci
][cj
],
219 id: this.getSquareId({x:ci
,y:cj
}),
228 if (this.mode
!= "idle")
233 on: { click: this.resign
},
234 attrs: { "aria-label": 'Resign' },
240 [h('i', { 'class': { "material-icons": true } }, "flag")])
243 else if (this.vr
.moves
.length
> 0)
245 // A game finished, and another is not started yet: allow navigation
246 actionArray
= actionArray
.concat([
249 style: { "margin-left": "30px" },
250 on: { click: e
=> this.undo() },
251 attrs: { "aria-label": 'Undo' },
253 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
256 on: { click: e
=> this.play() },
257 attrs: { "aria-label": 'Play' },
259 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
263 elementArray
.push(gameDiv
);
264 if (!!this.vr
.reserve
)
266 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
267 let myReservePiecesArray
= [];
268 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
270 myReservePiecesArray
.push(h('div',
272 'class': {'board':true, ['board'+sizeY
]:true},
273 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
278 'class': {"piece":true},
280 "src": "/images/pieces/" +
281 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
285 {style: { "padding-left":"40%"} },
286 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
290 let oppReservePiecesArray
= [];
291 const oppCol
= this.vr
.getOppCol(this.mycolor
);
292 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
294 oppReservePiecesArray
.push(h('div',
296 'class': {'board':true, ['board'+sizeY
]:true},
297 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
302 'class': {"piece":true},
304 "src": "/images/pieces/" +
305 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
309 {style: { "padding-left":"40%"} },
310 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
314 let reserves
= h('div',
316 'class':{'game':true},
317 style: {"margin-bottom": "20px"},
322 'class': { 'row': true },
323 style: {"margin-bottom": "15px"},
328 { 'class': { 'row': true }},
329 oppReservePiecesArray
333 elementArray
.push(reserves
);
335 const eogMessage
= this.getEndgameMessage(this.score
);
339 attrs: { "id": "modal-eog", type: "checkbox" },
340 "class": { "modal": true },
344 attrs: { "role": "dialog", "aria-labelledby": "modal-eog" },
349 "class": { "card": true, "smallpad": true },
354 attrs: { "for": "modal-eog" },
355 "class": { "modal-close": true },
360 "class": { "section": true },
361 domProps: { innerHTML: eogMessage
},
369 elementArray
= elementArray
.concat(modalEog
);
371 const modalNewgame
= [
374 attrs: { "id": "modal-newgame", type: "checkbox" },
375 "class": { "modal": true },
379 attrs: { "role": "dialog", "aria-labelledby": "modal-newgame" },
384 "class": { "card": true, "smallpad": true },
389 attrs: { "id": "close-newgame", "for": "modal-newgame" },
390 "class": { "modal-close": true },
395 "class": { "section": true },
396 domProps: { innerHTML: "New game" },
401 "class": { "section": true },
402 domProps: { innerHTML: "Waiting for opponent..." },
410 elementArray
= elementArray
.concat(modalNewgame
);
411 const actions
= h('div',
413 attrs: { "id": "actions" },
414 'class': { 'text-center': true },
418 elementArray
.push(actions
);
419 if (this.score
!= "*")
423 { attrs: { id: "pgn-div" } },
435 attrs: { id: "pgn-game" },
436 on: { click: this.download
},
437 domProps: { innerHTML: this.pgnTxt
}
444 else if (this.mode
!= "idle")
446 // Show current FEN (at least for debug)
449 { attrs: { id: "fen-div" } },
453 attrs: { id: "fen-string" },
454 domProps: { innerHTML: this.vr
.getBaseFen() }
467 "col-md-offset-2":true,
469 "col-lg-offset-3":true,
471 // NOTE: click = mousedown + mouseup
473 mousedown: this.mousedown
,
474 mousemove: this.mousemove
,
475 mouseup: this.mouseup
,
476 touchstart: this.mousedown
,
477 touchmove: this.mousemove
,
478 touchend: this.mouseup
,
484 created: function() {
485 const url
= socketUrl
;
486 const continuation
= (localStorage
.getItem("variant") === variant
);
487 this.myid
= continuation
488 ? localStorage
.getItem("myid")
489 // random enough (TODO: function)
490 : (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
493 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
494 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
496 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
497 const socketOpenListener
= () => {
500 const fen
= localStorage
.getItem("fen");
501 const mycolor
= localStorage
.getItem("mycolor");
502 const oppid
= localStorage
.getItem("oppid");
503 const moves
= JSON
.parse(localStorage
.getItem("moves"));
504 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
505 // Send ping to server (answer pong if opponent is connected)
506 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
508 else if (localStorage
.getItem("newgame") === variant
)
510 // New game request has been cancelled on disconnect
511 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
514 const socketMessageListener
= msg
=> {
515 const data
= JSON
.parse(msg
.data
);
518 case "newgame": //opponent found
519 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
521 case "newmove": //..he played!
522 this.play(data
.move, "animate");
524 case "pong": //received if we sent a ping (game still alive on our side)
525 this.oppConnected
= true;
526 const L
= this.vr
.moves
.length
;
527 // Send our "last state" informations to opponent
528 this.conn
.send(JSON
.stringify({
531 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
535 case "lastate": //got opponent infos about last move (we might have resigned)
536 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
539 this.conn
.send(JSON
.stringify({
546 else if (data
.movesCount
< 0)
549 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
551 else if (data
.movesCount
< this.vr
.moves
.length
)
553 // We must tell last move to opponent
554 const L
= this.vr
.moves
.length
;
555 this.conn
.send(JSON
.stringify({
558 lastMove:this.vr
.moves
[L
-1],
562 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
563 this.play(data
.lastMove
, "animate");
565 case "resign": //..you won!
566 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
568 // TODO: also use (dis)connect info to count online players?
571 if (this.mode
== "human" && this.oppid
== data
.id
)
572 this.oppConnected
= (data
.code
== "connect");
576 const socketCloseListener
= () => {
577 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
578 this.conn
.addEventListener('open', socketOpenListener
);
579 this.conn
.addEventListener('message', socketMessageListener
);
580 this.conn
.addEventListener('close', socketCloseListener
);
582 this.conn
.onopen
= socketOpenListener
;
583 this.conn
.onmessage
= socketMessageListener
;
584 this.conn
.onclose
= socketCloseListener
;
585 // Listen to keyboard left/right to navigate in game
586 document
.onkeydown
= event
=> {
587 if (this.mode
== "idle" && this.vr
.moves
.length
> 0
588 && [37,39].includes(event
.keyCode
))
590 event
.preventDefault();
591 if (event
.keyCode
== 37) //Back
599 download: function() {
600 let content
= document
.getElementById("pgn-game").innerHTML
;
601 content
= content
.replace(/<br>/g, "\n");
602 // Prepare and trigger download link
603 let downloadAnchor
= document
.getElementById("download");
604 downloadAnchor
.setAttribute("download", "game.pgn");
605 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
606 downloadAnchor
.click();
608 endGame: function(score
) {
610 let modalBox
= document
.getElementById("modal-eog");
611 modalBox
.checked
= true;
612 // Variants may have special PGN structure (so next function isn't defined here)
613 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
614 setTimeout(() => { modalBox
.checked
= false; }, 2000);
615 if (this.mode
== "human")
618 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
621 getEndgameMessage: function(score
) {
622 let eogMessage
= "Unfinished";
626 eogMessage
= "White win";
629 eogMessage
= "Black win";
637 setStorage: function() {
638 localStorage
.setItem("myid", this.myid
);
639 localStorage
.setItem("variant", variant
);
640 localStorage
.setItem("mycolor", this.mycolor
);
641 localStorage
.setItem("oppid", this.oppid
);
642 localStorage
.setItem("fenStart", this.fenStart
);
643 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
644 localStorage
.setItem("fen", this.vr
.getFen());
646 updateStorage: function() {
647 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
648 localStorage
.setItem("fen", this.vr
.getFen());
650 clearStorage: function() {
651 delete localStorage
["variant"];
652 delete localStorage
["myid"];
653 delete localStorage
["mycolor"];
654 delete localStorage
["oppid"];
655 delete localStorage
["fenStart"];
656 delete localStorage
["fen"];
657 delete localStorage
["moves"];
659 // HACK because mini-css tooltips are persistent after click...
660 getRidOfTooltip: function(elt
) {
661 elt
.style
.visibility
= "hidden";
662 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
664 clickGameSeek: function(e
) {
665 this.getRidOfTooltip(e
.currentTarget
);
666 if (this.mode
== "human")
667 return; //no newgame while playing
670 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
671 delete localStorage
["newgame"]; //cancel game seek
675 this.newGame("human");
677 clickComputerGame: function(e
) {
678 this.getRidOfTooltip(e
.currentTarget
);
679 if (this.mode
== "human")
680 return; //no newgame while playing
681 this.newGame("computer");
683 toggleExpertMode: function(e
) {
684 this.getRidOfTooltip(e
.currentTarget
);
685 this.expert
= !this.expert
;
686 document
.cookie
= "expert=" + (this.expert
? "1" : "0");
689 if (this.mode
== "human" && this.oppConnected
)
692 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
693 } catch (INVALID_STATE_ERR
) {
694 return; //socket is not ready (and not yet reconnected)
697 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
699 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
700 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
701 console
.log(fen
); //DEBUG
702 if (mode
=="human" && !oppId
)
704 const storageVariant
= localStorage
.getItem("variant");
705 if (!!storageVariant
&& storageVariant
!== variant
)
707 alert("Finish your " + storageVariant
+ " game first!");
710 // Send game request and wait..
711 localStorage
["newgame"] = variant
;
713 this.clearStorage(); //in case of
715 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
716 } catch (INVALID_STATE_ERR
) {
717 return; //nothing achieved
719 if (continuation
!== "reconnect") //TODO: bad HACK...
721 let modalBox
= document
.getElementById("modal-newgame");
722 modalBox
.checked
= true;
723 setTimeout(() => { modalBox
.checked
= false; }, 2000);
727 // random enough (TODO: function)
728 this.gameId
= (Date
.now().toString(36) + Math
.random().toString(36).substr(2, 7)).toUpperCase();
729 this.vr
= new VariantRules(fen
, moves
|| []);
731 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
733 this.incheck
= []; //in case of
734 this.fenStart
= continuation
735 ? localStorage
.getItem("fenStart")
736 : fen
.split(" ")[0]; //Only the position matters
742 // Not playing sound on game continuation:
743 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
744 document
.getElementById("modal-newgame").checked
= false;
747 this.oppConnected
= true;
748 this.mycolor
= color
;
750 if (!!moves
&& moves
.length
> 0) //imply continuation
752 const lastMove
= moves
[moves
.length
-1];
753 this.vr
.undo(lastMove
);
754 this.incheck
= this.vr
.getCheckSquares(lastMove
);
755 this.vr
.play(lastMove
, "ingame");
757 delete localStorage
["newgame"];
758 this.setStorage(); //in case of interruptions
760 else //against computer
762 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
763 if (this.mycolor
== 'b')
764 setTimeout(this.playComputerMove
, 500);
767 playComputerMove: function() {
768 const timeStart
= Date
.now();
769 const nbMoves
= this.vr
.moves
.length
; //using played moves to know if search finished
770 const gameId
= this.gameId
; //to know if game was reset before timer end
773 if (gameId
!= this.gameId
)
774 return; //game stopped
775 const L
= this.vr
.moves
.length
;
776 if (nbMoves
== L
|| !this.vr
.moves
[L
-1].notation
) //move search didn't finish
777 this.vr
.shouldReturn
= true;
779 const compMove
= this.vr
.getComputerMove();
780 // (first move) HACK: avoid selecting elements before they appear on page:
781 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
782 setTimeout(() => this.play(compMove
, "animate"), delay
);
784 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
785 getSquareId: function(o
) {
786 // NOTE: a separator is required to allow any size of board
787 return "sq-" + o
.x
+ "-" + o
.y
;
790 getSquareFromId: function(id
) {
791 let idParts
= id
.split('-');
792 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
794 mousedown: function(e
) {
795 e
= e
|| window
.event
;
798 while (!ingame
&& elem
!== null)
800 if (elem
.classList
.contains("game"))
805 elem
= elem
.parentElement
;
807 if (!ingame
) //let default behavior (click on button...)
809 e
.preventDefault(); //disable native drag & drop
810 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
812 // Next few lines to center the piece on mouse cursor
813 let rect
= e
.target
.parentNode
.getBoundingClientRect();
815 x: rect
.x
+ rect
.width
/2,
816 y: rect
.y
+ rect
.width
/2,
817 id: e
.target
.parentNode
.id
819 this.selectedPiece
= e
.target
.cloneNode();
820 this.selectedPiece
.style
.position
= "absolute";
821 this.selectedPiece
.style
.top
= 0;
822 this.selectedPiece
.style
.display
= "inline-block";
823 this.selectedPiece
.style
.zIndex
= 3000;
824 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
825 this.possibleMoves
= this.mode
!="idle" && this.vr
.canIplay(this.mycolor
,startSquare
)
826 ? this.vr
.getPossibleMovesFrom(startSquare
)
828 // Next line add moving piece just after current image (required for Crazyhouse reserve)
829 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
832 mousemove: function(e
) {
833 if (!this.selectedPiece
)
835 e
= e
|| window
.event
;
836 // If there is an active element, move it around
837 if (!!this.selectedPiece
)
839 const [offsetX
,offsetY
] = !!e
.clientX
840 ? [e
.clientX
,e
.clientY
] //desktop browser
841 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
842 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
843 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
846 mouseup: function(e
) {
847 if (!this.selectedPiece
)
849 e
= e
|| window
.event
;
850 // Read drop target (or parentElement, parentNode... if type == "img")
851 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
852 const [offsetX
,offsetY
] = !!e
.clientX
853 ? [e
.clientX
,e
.clientY
]
854 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
855 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
856 this.selectedPiece
.style
.zIndex
= 3000;
857 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
858 landing
= landing
.parentNode
;
859 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
861 // OK: process move attempt
862 let endSquare
= this.getSquareFromId(landing
.id
);
863 let moves
= this.findMatchingMoves(endSquare
);
864 this.possibleMoves
= [];
865 if (moves
.length
> 1)
866 this.choices
= moves
;
867 else if (moves
.length
==1)
869 // Else: impossible move
870 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
871 delete this.selectedPiece
;
872 this.selectedPiece
= null;
874 findMatchingMoves: function(endSquare
) {
875 // Run through moves list and return the matching set (if promotions...)
877 this.possibleMoves
.forEach(function(m
) {
878 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
883 animateMove: function(move) {
884 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
885 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
886 let rectStart
= startSquare
.getBoundingClientRect();
887 let rectEnd
= endSquare
.getBoundingClientRect();
888 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
890 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
891 // HACK for animation (with positive translate, image slides "under background"...)
892 // Possible improvement: just alter squares on the piece's way...
893 squares
= document
.getElementsByClassName("board");
894 for (let i
=0; i
<squares
.length
; i
++)
896 let square
= squares
.item(i
);
897 if (square
.id
!= this.getSquareId(move.start
))
898 square
.style
.zIndex
= "-1";
900 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
901 movingPiece
.style
.transitionDuration
= "0.2s";
902 movingPiece
.style
.zIndex
= "3000";
904 for (let i
=0; i
<squares
.length
; i
++)
905 squares
.item(i
).style
.zIndex
= "auto";
906 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
910 play: function(move, programmatic
) {
913 // Navigate after game is over
914 if (this.cursor
>= this.vr
.moves
.length
)
915 return; //already at the end
916 move = this.vr
.moves
[this.cursor
++];
918 if (!!programmatic
) //computer or human opponent
920 this.animateMove(move);
923 // Not programmatic, or animation is over
924 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
925 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
926 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
927 if (this.mode
!= "idle")
929 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
930 this.vr
.play(move, "ingame");
934 VariantRules
.PlayOnBoard(this.vr
.board
, move);
935 this.$forceUpdate(); //TODO: ?!
937 if (this.mode
== "human")
938 this.updateStorage(); //after our moves and opponent moves
939 if (this.mode
!= "idle")
941 const eog
= this.vr
.checkGameOver();
945 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
946 setTimeout(this.playComputerMove
, 500);
949 // Navigate after game is over
950 if (this.cursor
== 0)
951 return; //already at the beginning
952 if (this.cursor
== this.vr
.moves
.length
)
953 this.incheck
= []; //in case of...
954 const move = this.vr
.moves
[--this.cursor
];
955 VariantRules
.UndoOnBoard(this.vr
.board
, move);
956 this.$forceUpdate(); //TODO: ?!