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, friend, computer or idle (when not playing)
13 oppid: "", //opponent ID in case of HH game
19 expert: getCookie("expert") === "1" ? true : 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
= [];
33 if (["idle","human"].includes(this.mode
))
38 on: { click: this.clickGameSeek
},
39 attrs: { "aria-label": 'New online game' },
42 "bottom": true, //display below
44 "playing": this.mode
== "human",
47 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
50 if (["idle","computer"].includes(this.mode
))
55 on: { click: this.clickComputerGame
},
56 attrs: { "aria-label": 'New game VS computer' },
60 "playing": this.mode
== "computer",
63 [h('i', { 'class': { "material-icons": true } }, "computer")])
66 if (["idle","friend"].includes(this.mode
))
71 on: { click: this.clickFriendGame
},
72 attrs: { "aria-label": 'New IRL game' },
76 "playing": this.mode
== "friend",
79 [h('i', { 'class': { "material-icons": true } }, "people")])
84 const square00
= document
.getElementById("sq-0-0");
85 const squareWidth
= !!square00
86 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
88 const indicWidth
= (squareWidth
>0 ? squareWidth
/2 : 20);
89 if (this.mode
== "human")
91 let connectedIndic
= h(
97 "connected": this.oppConnected
,
98 "disconnected": !this.oppConnected
,
101 "width": indicWidth
+ "px",
102 "height": indicWidth
+ "px",
106 elementArray
.push(connectedIndic
);
112 "topindicator": true,
114 "white-turn": this.vr
.turn
=="w",
115 "black-turn": this.vr
.turn
=="b",
118 "width": indicWidth
+ "px",
119 "height": indicWidth
+ "px",
123 elementArray
.push(turnIndic
);
124 let expertSwitch
= h(
127 on: { click: this.toggleExpertMode
},
128 attrs: { "aria-label": 'Toggle expert mode' },
131 "topindicator": true,
133 "expert-switch": true,
134 "expert-mode": this.expert
,
137 [h('i', { 'class': { "material-icons": true } }, "visibility_off")]
139 elementArray
.push(expertSwitch
);
140 let choices
= h('div',
142 attrs: { "id": "choices" },
143 'class': { 'row': true },
145 "display": this.choices
.length
>0?"block":"none",
146 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
147 "width": (this.choices
.length
* squareWidth
) + "px",
148 "height": squareWidth
+ "px",
151 this.choices
.map( m
=> { //a "choice" is a move
156 ['board'+sizeY
]: true,
159 'width': (100/this.choices
.length
) + "%",
160 'padding-bottom': (100/this.choices
.length
) + "%",
165 attrs: { "src": '/images/pieces/' +
166 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
167 'class': { 'choice-piece': true },
168 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
174 // Create board element (+ reserves if needed by variant or mode)
175 let gameDiv
= h('div',
177 'class': { 'game': true },
179 [_
.range(sizeX
).map(i
=> {
180 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
187 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
189 _
.range(sizeY
).map(j
=> {
190 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
192 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
200 'ghost': !!this.selectedPiece
201 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
204 src: "/images/pieces/" +
205 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
211 if (!this.expert
&& hintSquares
[ci
][cj
])
221 src: "/images/mark.svg",
227 const lm
= this.vr
.lastMove
;
228 const showLight
= !this.expert
&&
229 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
235 ['board'+sizeY
]: true,
236 'light-square': (i
+j
)%2==0,
237 'dark-square': (i
+j
)%2==1,
238 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
239 'incheck': showLight
&& incheckSq
[ci
][cj
],
242 id: this.getSquareId({x:ci
,y:cj
}),
251 if (this.mode
!= "idle")
256 on: { click: this.resign
},
257 attrs: { "aria-label": 'Resign' },
263 [h('i', { 'class': { "material-icons": true } }, "flag")])
266 else if (this.vr
.moves
.length
> 0)
268 // A game finished, and another is not started yet: allow navigation
269 actionArray
= actionArray
.concat([
272 style: { "margin-left": "30px" },
273 on: { click: e
=> this.undo() },
274 attrs: { "aria-label": 'Undo' },
276 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
279 on: { click: e
=> this.play() },
280 attrs: { "aria-label": 'Play' },
282 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
286 if (this.mode
== "friend")
288 actionArray
= actionArray
.concat(
292 style: { "margin-left": "30px" },
293 on: { click: this.undoInGame
},
294 attrs: { "aria-label": 'Undo' },
296 [h('i', { 'class': { "material-icons": true } }, "undo")]
300 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
301 attrs: { "aria-label": 'Flip' },
303 [h('i', { 'class': { "material-icons": true } }, "cached")]
307 elementArray
.push(gameDiv
);
308 if (!!this.vr
.reserve
)
310 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
311 let myReservePiecesArray
= [];
312 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
314 myReservePiecesArray
.push(h('div',
316 'class': {'board':true, ['board'+sizeY
]:true},
317 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
322 'class': {"piece":true},
324 "src": "/images/pieces/" +
325 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
329 {style: { "padding-left":"40%"} },
330 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
334 let oppReservePiecesArray
= [];
335 const oppCol
= this.vr
.getOppCol(this.mycolor
);
336 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
338 oppReservePiecesArray
.push(h('div',
340 'class': {'board':true, ['board'+sizeY
]:true},
341 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
346 'class': {"piece":true},
348 "src": "/images/pieces/" +
349 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
353 {style: { "padding-left":"40%"} },
354 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
358 let reserves
= h('div',
360 'class':{'game':true},
361 style: {"margin-bottom": "20px"},
366 'class': { 'row': true },
367 style: {"margin-bottom": "15px"},
372 { 'class': { 'row': true }},
373 oppReservePiecesArray
377 elementArray
.push(reserves
);
379 const eogMessage
= this.getEndgameMessage(this.score
);
383 attrs: { "id": "modal-eog", type: "checkbox" },
384 "class": { "modal": true },
388 attrs: { "role": "dialog", "aria-labelledby": "modal-eog" },
393 "class": { "card": true, "smallpad": true },
398 attrs: { "for": "modal-eog" },
399 "class": { "modal-close": true },
404 "class": { "section": true },
405 domProps: { innerHTML: eogMessage
},
413 elementArray
= elementArray
.concat(modalEog
);
415 const modalNewgame
= [
418 attrs: { "id": "modal-newgame", type: "checkbox" },
419 "class": { "modal": true },
423 attrs: { "role": "dialog", "aria-labelledby": "modal-newgame" },
428 "class": { "card": true, "smallpad": true },
433 attrs: { "id": "close-newgame", "for": "modal-newgame" },
434 "class": { "modal-close": true },
439 "class": { "section": true },
440 domProps: { innerHTML: "New game" },
445 "class": { "section": true },
446 domProps: { innerHTML: "Waiting for opponent..." },
454 elementArray
= elementArray
.concat(modalNewgame
);
455 const modalFenEdit
= [
458 attrs: { "id": "modal-fenedit", type: "checkbox" },
459 "class": { "modal": true },
463 attrs: { "role": "dialog", "aria-labelledby": "modal-fenedit" },
468 "class": { "card": true, "smallpad": true },
473 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
474 "class": { "modal-close": true },
479 "class": { "section": true },
480 domProps: { innerHTML: "Position + flags (FEN):" },
488 value: VariantRules
.GenRandInitFen(),
496 const fen
= document
.getElementById("input-fen").value
;
497 document
.getElementById("modal-fenedit").checked
= false;
498 this.newGame("friend", fen
);
501 domProps: { innerHTML: "Ok" },
508 document
.getElementById("input-fen").value
=
509 VariantRules
.GenRandInitFen();
512 domProps: { innerHTML: "Random" },
520 elementArray
= elementArray
.concat(modalFenEdit
);
521 const actions
= h('div',
523 attrs: { "id": "actions" },
524 'class': { 'text-center': true },
528 elementArray
.push(actions
);
529 if (this.score
!= "*")
533 { attrs: { id: "pgn-div" } },
545 attrs: { id: "pgn-game" },
546 on: { click: this.download
},
547 domProps: { innerHTML: this.pgnTxt
}
554 else if (this.mode
!= "idle")
559 { attrs: { id: "fen-div" } },
563 attrs: { id: "fen-string" },
564 domProps: { innerHTML: this.vr
.getFen() }
577 "col-md-offset-2":true,
579 "col-lg-offset-3":true,
581 // NOTE: click = mousedown + mouseup
583 mousedown: this.mousedown
,
584 mousemove: this.mousemove
,
585 mouseup: this.mouseup
,
586 touchstart: this.mousedown
,
587 touchmove: this.mousemove
,
588 touchend: this.mouseup
,
594 created: function() {
595 const url
= socketUrl
;
596 const continuation
= (localStorage
.getItem("variant") === variant
);
597 this.myid
= continuation
? localStorage
.getItem("myid") : getRandString();
600 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
601 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
603 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
604 const socketOpenListener
= () => {
607 const fen
= localStorage
.getItem("fen");
608 const mycolor
= localStorage
.getItem("mycolor");
609 const oppid
= localStorage
.getItem("oppid");
610 const moves
= JSON
.parse(localStorage
.getItem("moves"));
611 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
612 // Send ping to server (answer pong if opponent is connected)
613 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
615 else if (localStorage
.getItem("newgame") === variant
)
617 // New game request has been cancelled on disconnect
618 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
621 const socketMessageListener
= msg
=> {
622 const data
= JSON
.parse(msg
.data
);
625 case "newgame": //opponent found
626 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
628 case "newmove": //..he played!
629 this.play(data
.move, "animate");
631 case "pong": //received if we sent a ping (game still alive on our side)
632 this.oppConnected
= true;
633 const L
= this.vr
.moves
.length
;
634 // Send our "last state" informations to opponent
635 this.conn
.send(JSON
.stringify({
638 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
642 case "lastate": //got opponent infos about last move (we might have resigned)
643 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
646 this.conn
.send(JSON
.stringify({
653 else if (data
.movesCount
< 0)
656 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
658 else if (data
.movesCount
< this.vr
.moves
.length
)
660 // We must tell last move to opponent
661 const L
= this.vr
.moves
.length
;
662 this.conn
.send(JSON
.stringify({
665 lastMove:this.vr
.moves
[L
-1],
669 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
670 this.play(data
.lastMove
, "animate");
672 case "resign": //..you won!
673 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
675 // TODO: also use (dis)connect info to count online players?
678 if (this.mode
== "human" && this.oppid
== data
.id
)
679 this.oppConnected
= (data
.code
== "connect");
683 const socketCloseListener
= () => {
684 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
685 this.conn
.addEventListener('open', socketOpenListener
);
686 this.conn
.addEventListener('message', socketMessageListener
);
687 this.conn
.addEventListener('close', socketCloseListener
);
689 this.conn
.onopen
= socketOpenListener
;
690 this.conn
.onmessage
= socketMessageListener
;
691 this.conn
.onclose
= socketCloseListener
;
692 // Listen to keyboard left/right to navigate in game
693 document
.onkeydown
= event
=> {
694 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
695 && [37,39].includes(event
.keyCode
))
697 event
.preventDefault();
698 if (event
.keyCode
== 37) //Back
706 download: function() {
707 let content
= document
.getElementById("pgn-game").innerHTML
;
708 content
= content
.replace(/<br>/g, "\n");
709 // Prepare and trigger download link
710 let downloadAnchor
= document
.getElementById("download");
711 downloadAnchor
.setAttribute("download", "game.pgn");
712 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
713 downloadAnchor
.click();
715 endGame: function(score
) {
717 let modalBox
= document
.getElementById("modal-eog");
718 modalBox
.checked
= true;
719 // Variants may have special PGN structure (so next function isn't defined here)
720 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
721 setTimeout(() => { modalBox
.checked
= false; }, 2000);
722 if (this.mode
== "human")
725 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
728 getEndgameMessage: function(score
) {
729 let eogMessage
= "Unfinished";
733 eogMessage
= "White win";
736 eogMessage
= "Black win";
744 setStorage: function() {
745 localStorage
.setItem("myid", this.myid
);
746 localStorage
.setItem("variant", variant
);
747 localStorage
.setItem("mycolor", this.mycolor
);
748 localStorage
.setItem("oppid", this.oppid
);
749 localStorage
.setItem("fenStart", this.fenStart
);
750 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
751 localStorage
.setItem("fen", this.vr
.getFen());
753 updateStorage: function() {
754 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
755 localStorage
.setItem("fen", this.vr
.getFen());
757 clearStorage: function() {
758 delete localStorage
["variant"];
759 delete localStorage
["myid"];
760 delete localStorage
["mycolor"];
761 delete localStorage
["oppid"];
762 delete localStorage
["fenStart"];
763 delete localStorage
["fen"];
764 delete localStorage
["moves"];
766 // HACK because mini-css tooltips are persistent after click...
767 getRidOfTooltip: function(elt
) {
768 elt
.style
.visibility
= "hidden";
769 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
771 clickGameSeek: function(e
) {
772 this.getRidOfTooltip(e
.currentTarget
);
773 if (this.mode
== "human")
774 return; //no newgame while playing
777 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
778 delete localStorage
["newgame"]; //cancel game seek
782 this.newGame("human");
784 clickComputerGame: function(e
) {
785 this.getRidOfTooltip(e
.currentTarget
);
786 if (this.mode
== "human")
787 return; //no newgame while playing
788 this.newGame("computer");
790 clickFriendGame: function(e
) {
791 this.getRidOfTooltip(e
.currentTarget
);
792 document
.getElementById("modal-fenedit").checked
= true;
794 toggleExpertMode: function(e
) {
795 this.getRidOfTooltip(e
.currentTarget
);
796 this.expert
= !this.expert
;
797 setCookie("expert", this.expert
? "1" : "0");
799 resign: function(e
) {
800 this.getRidOfTooltip(e
.currentTarget
);
801 if (this.mode
== "human" && this.oppConnected
)
804 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
805 } catch (INVALID_STATE_ERR
) {
806 return; //socket is not ready (and not yet reconnected)
809 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
811 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
812 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
813 console
.log(fen
); //DEBUG
814 if (mode
=="human" && !oppId
)
816 const storageVariant
= localStorage
.getItem("variant");
817 if (!!storageVariant
&& storageVariant
!== variant
)
819 alert("Finish your " + storageVariant
+ " game first!");
822 // Send game request and wait..
823 localStorage
["newgame"] = variant
;
825 this.clearStorage(); //in case of
827 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
828 } catch (INVALID_STATE_ERR
) {
829 return; //nothing achieved
831 if (continuation
!== "reconnect") //TODO: bad HACK...
833 let modalBox
= document
.getElementById("modal-newgame");
834 modalBox
.checked
= true;
835 setTimeout(() => { modalBox
.checked
= false; }, 2000);
839 this.gameId
= getRandString();
840 this.vr
= new VariantRules(fen
, moves
|| []);
842 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
844 this.incheck
= []; //in case of
845 this.fenStart
= (continuation
? localStorage
.getItem("fenStart") : fen
);
851 // Not playing sound on game continuation:
852 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
853 document
.getElementById("modal-newgame").checked
= false;
856 this.oppConnected
= true;
857 this.mycolor
= color
;
859 if (!!moves
&& moves
.length
> 0) //imply continuation
861 const lastMove
= moves
[moves
.length
-1];
862 this.vr
.undo(lastMove
);
863 this.incheck
= this.vr
.getCheckSquares(lastMove
);
864 this.vr
.play(lastMove
, "ingame");
866 delete localStorage
["newgame"];
867 this.setStorage(); //in case of interruptions
869 else if (mode
== "computer")
871 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
872 if (this.mycolor
== 'b')
873 setTimeout(this.playComputerMove
, 500);
875 //else: against a (IRL) friend: nothing more to do
877 playComputerMove: function() {
878 const timeStart
= Date
.now();
879 const nbMoves
= this.vr
.moves
.length
; //using played moves to know if search finished
880 const gameId
= this.gameId
; //to know if game was reset before timer end
883 if (gameId
!= this.gameId
)
884 return; //game stopped
885 const L
= this.vr
.moves
.length
;
886 if (nbMoves
== L
|| !this.vr
.moves
[L
-1].notation
) //move search didn't finish
887 this.vr
.shouldReturn
= true;
889 const compMove
= this.vr
.getComputerMove();
890 // (first move) HACK: avoid selecting elements before they appear on page:
891 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
892 setTimeout(() => this.play(compMove
, "animate"), delay
);
894 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
895 getSquareId: function(o
) {
896 // NOTE: a separator is required to allow any size of board
897 return "sq-" + o
.x
+ "-" + o
.y
;
900 getSquareFromId: function(id
) {
901 let idParts
= id
.split('-');
902 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
904 mousedown: function(e
) {
905 e
= e
|| window
.event
;
908 while (!ingame
&& elem
!== null)
910 if (elem
.classList
.contains("game"))
915 elem
= elem
.parentElement
;
917 if (!ingame
) //let default behavior (click on button...)
919 e
.preventDefault(); //disable native drag & drop
920 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
922 // Next few lines to center the piece on mouse cursor
923 let rect
= e
.target
.parentNode
.getBoundingClientRect();
925 x: rect
.x
+ rect
.width
/2,
926 y: rect
.y
+ rect
.width
/2,
927 id: e
.target
.parentNode
.id
929 this.selectedPiece
= e
.target
.cloneNode();
930 this.selectedPiece
.style
.position
= "absolute";
931 this.selectedPiece
.style
.top
= 0;
932 this.selectedPiece
.style
.display
= "inline-block";
933 this.selectedPiece
.style
.zIndex
= 3000;
934 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
935 const iCanPlay
= this.mode
!="idle"
936 && (this.mode
=="friend" || this.vr
.canIplay(this.mycolor
,startSquare
));
937 this.possibleMoves
= iCanPlay
? this.vr
.getPossibleMovesFrom(startSquare
) : [];
938 // Next line add moving piece just after current image (required for Crazyhouse reserve)
939 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
942 mousemove: function(e
) {
943 if (!this.selectedPiece
)
945 e
= e
|| window
.event
;
946 // If there is an active element, move it around
947 if (!!this.selectedPiece
)
949 const [offsetX
,offsetY
] = !!e
.clientX
950 ? [e
.clientX
,e
.clientY
] //desktop browser
951 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
952 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
953 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
956 mouseup: function(e
) {
957 if (!this.selectedPiece
)
959 e
= e
|| window
.event
;
960 // Read drop target (or parentElement, parentNode... if type == "img")
961 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
962 const [offsetX
,offsetY
] = !!e
.clientX
963 ? [e
.clientX
,e
.clientY
]
964 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
965 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
966 this.selectedPiece
.style
.zIndex
= 3000;
967 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
968 landing
= landing
.parentNode
;
969 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
971 // OK: process move attempt
972 let endSquare
= this.getSquareFromId(landing
.id
);
973 let moves
= this.findMatchingMoves(endSquare
);
974 this.possibleMoves
= [];
975 if (moves
.length
> 1)
976 this.choices
= moves
;
977 else if (moves
.length
==1)
979 // Else: impossible move
980 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
981 delete this.selectedPiece
;
982 this.selectedPiece
= null;
984 findMatchingMoves: function(endSquare
) {
985 // Run through moves list and return the matching set (if promotions...)
987 this.possibleMoves
.forEach(function(m
) {
988 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
993 animateMove: function(move) {
994 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
995 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
996 let rectStart
= startSquare
.getBoundingClientRect();
997 let rectEnd
= endSquare
.getBoundingClientRect();
998 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1000 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1001 // HACK for animation (with positive translate, image slides "under background"...)
1002 // Possible improvement: just alter squares on the piece's way...
1003 squares
= document
.getElementsByClassName("board");
1004 for (let i
=0; i
<squares
.length
; i
++)
1006 let square
= squares
.item(i
);
1007 if (square
.id
!= this.getSquareId(move.start
))
1008 square
.style
.zIndex
= "-1";
1010 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
1011 movingPiece
.style
.transitionDuration
= "0.2s";
1012 movingPiece
.style
.zIndex
= "3000";
1014 for (let i
=0; i
<squares
.length
; i
++)
1015 squares
.item(i
).style
.zIndex
= "auto";
1016 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1020 play: function(move, programmatic
) {
1023 // Navigate after game is over
1024 if (this.cursor
>= this.vr
.moves
.length
)
1025 return; //already at the end
1026 move = this.vr
.moves
[this.cursor
++];
1028 if (!!programmatic
) //computer or human opponent
1030 this.animateMove(move);
1033 // Not programmatic, or animation is over
1034 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1035 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1036 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
1037 if (this.mode
!= "idle")
1039 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1040 this.vr
.play(move, "ingame");
1044 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1045 this.$forceUpdate(); //TODO: ?!
1047 if (this.mode
== "human")
1048 this.updateStorage(); //after our moves and opponent moves
1049 if (this.mode
!= "idle")
1051 const eog
= this.vr
.checkGameOver();
1055 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1056 setTimeout(this.playComputerMove
, 500);
1059 // Navigate after game is over
1060 if (this.cursor
== 0)
1061 return; //already at the beginning
1062 if (this.cursor
== this.vr
.moves
.length
)
1063 this.incheck
= []; //in case of...
1064 const move = this.vr
.moves
[--this.cursor
];
1065 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1066 this.$forceUpdate(); //TODO: ?!
1068 undoInGame: function() {
1069 const lm
= this.vr
.lastMove
;