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 const smallScreen
= (screen
.width
<= 420);
26 // Precompute hints squares to facilitate rendering
27 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
28 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
29 // Also precompute in-check squares
30 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
31 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
32 let elementArray
= [];
37 on: { click: this.clickGameSeek
},
38 attrs: { "aria-label": 'New online game' },
41 "bottom": true, //display below
43 "playing": this.mode
== "human",
47 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
49 if (["idle","computer"].includes(this.mode
))
54 on: { click: this.clickComputerGame
},
55 attrs: { "aria-label": 'New game VS computer' },
59 "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",
80 [h('i', { 'class': { "material-icons": true } }, "people")])
85 const square00
= document
.getElementById("sq-0-0");
86 const squareWidth
= !!square00
87 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
89 const indicWidth
= (squareWidth
>0 ? squareWidth
/2 : 20);
90 if (this.mode
== "human")
92 let connectedIndic
= h(
98 "connected": this.oppConnected
,
99 "disconnected": !this.oppConnected
,
102 "width": indicWidth
+ "px",
103 "height": indicWidth
+ "px",
107 elementArray
.push(connectedIndic
);
113 "topindicator": true,
115 "white-turn": this.vr
.turn
=="w",
116 "black-turn": this.vr
.turn
=="b",
119 "width": indicWidth
+ "px",
120 "height": indicWidth
+ "px",
124 elementArray
.push(turnIndic
);
125 let expertSwitch
= h(
128 on: { click: this.toggleExpertMode
},
129 attrs: { "aria-label": 'Toggle expert mode' },
130 style: { "padding-top": "0", "margin-top": "0" },
133 "topindicator": true,
135 "expert-switch": true,
136 "expert-mode": this.expert
,
137 "small": smallScreen
,
140 [h('i', { 'class': { "material-icons": true } }, "visibility_off")]
142 elementArray
.push(expertSwitch
);
143 let choices
= h('div',
145 attrs: { "id": "choices" },
146 'class': { 'row': true },
148 "display": this.choices
.length
>0?"block":"none",
149 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
150 "width": (this.choices
.length
* squareWidth
) + "px",
151 "height": squareWidth
+ "px",
154 this.choices
.map( m
=> { //a "choice" is a move
159 ['board'+sizeY
]: true,
162 'width': (100/this.choices
.length
) + "%",
163 'padding-bottom': (100/this.choices
.length
) + "%",
168 attrs: { "src": '/images/pieces/' +
169 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
170 'class': { 'choice-piece': true },
171 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
177 // Create board element (+ reserves if needed by variant or mode)
178 let gameDiv
= h('div',
180 'class': { 'game': true },
182 [_
.range(sizeX
).map(i
=> {
183 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
190 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
192 _
.range(sizeY
).map(j
=> {
193 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
195 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
203 'ghost': !!this.selectedPiece
204 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
207 src: "/images/pieces/" +
208 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
214 if (!this.expert
&& hintSquares
[ci
][cj
])
224 src: "/images/mark.svg",
230 const lm
= this.vr
.lastMove
;
231 const showLight
= !this.expert
&&
232 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
238 ['board'+sizeY
]: true,
239 'light-square': (i
+j
)%2==0,
240 'dark-square': (i
+j
)%2==1,
241 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
242 'incheck': showLight
&& incheckSq
[ci
][cj
],
245 id: this.getSquareId({x:ci
,y:cj
}),
254 if (this.mode
!= "idle")
259 on: { click: this.resign
},
260 attrs: { "aria-label": 'Resign' },
264 "small": smallScreen
,
267 [h('i', { 'class': { "material-icons": true } }, "flag")])
270 else if (this.vr
.moves
.length
> 0)
272 // A game finished, and another is not started yet: allow navigation
273 actionArray
= actionArray
.concat([
276 style: { "margin-left": "30px" },
277 on: { click: e
=> this.undo() },
278 attrs: { "aria-label": 'Undo' },
279 "class": { "small": smallScreen
},
281 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
284 on: { click: e
=> this.play() },
285 attrs: { "aria-label": 'Play' },
286 "class": { "small": smallScreen
},
288 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
292 if (this.mode
== "friend")
294 actionArray
= actionArray
.concat(
298 style: { "margin-left": "30px" },
299 on: { click: this.undoInGame
},
300 attrs: { "aria-label": 'Undo' },
301 "class": { "small": smallScreen
},
303 [h('i', { 'class': { "material-icons": true } }, "undo")]
307 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
308 attrs: { "aria-label": 'Flip' },
309 "class": { "small": smallScreen
},
311 [h('i', { 'class': { "material-icons": true } }, "cached")]
315 elementArray
.push(gameDiv
);
316 if (!!this.vr
.reserve
)
318 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
319 let myReservePiecesArray
= [];
320 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
322 myReservePiecesArray
.push(h('div',
324 'class': {'board':true, ['board'+sizeY
]:true},
325 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
330 'class': {"piece":true},
332 "src": "/images/pieces/" +
333 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
337 {style: { "padding-left":"40%"} },
338 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
342 let oppReservePiecesArray
= [];
343 const oppCol
= this.vr
.getOppCol(this.mycolor
);
344 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
346 oppReservePiecesArray
.push(h('div',
348 'class': {'board':true, ['board'+sizeY
]:true},
349 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
354 'class': {"piece":true},
356 "src": "/images/pieces/" +
357 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
361 {style: { "padding-left":"40%"} },
362 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
366 let reserves
= h('div',
368 'class':{'game':true},
369 style: {"margin-bottom": "20px"},
374 'class': { 'row': true },
375 style: {"margin-bottom": "15px"},
380 { 'class': { 'row': true }},
381 oppReservePiecesArray
385 elementArray
.push(reserves
);
387 const eogMessage
= this.getEndgameMessage(this.score
);
391 attrs: { "id": "modal-eog", type: "checkbox" },
392 "class": { "modal": true },
396 attrs: { "role": "dialog", "aria-labelledby": "modal-eog" },
401 "class": { "card": true, "smallpad": true },
406 attrs: { "for": "modal-eog" },
407 "class": { "modal-close": true },
412 "class": { "section": true },
413 domProps: { innerHTML: eogMessage
},
421 elementArray
= elementArray
.concat(modalEog
);
423 const modalNewgame
= [
426 attrs: { "id": "modal-newgame", type: "checkbox" },
427 "class": { "modal": true },
431 attrs: { "role": "dialog", "aria-labelledby": "modal-newgame" },
436 "class": { "card": true, "smallpad": true },
441 attrs: { "id": "close-newgame", "for": "modal-newgame" },
442 "class": { "modal-close": true },
447 "class": { "section": true },
448 domProps: { innerHTML: "New game" },
453 "class": { "section": true },
454 domProps: { innerHTML: "Waiting for opponent..." },
462 elementArray
= elementArray
.concat(modalNewgame
);
463 const modalFenEdit
= [
466 attrs: { "id": "modal-fenedit", type: "checkbox" },
467 "class": { "modal": true },
471 attrs: { "role": "dialog", "aria-labelledby": "modal-fenedit" },
476 "class": { "card": true, "smallpad": true },
481 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
482 "class": { "modal-close": true },
487 "class": { "section": true },
488 domProps: { innerHTML: "Position + flags (FEN):" },
496 value: VariantRules
.GenRandInitFen(),
504 const fen
= document
.getElementById("input-fen").value
;
505 document
.getElementById("modal-fenedit").checked
= false;
506 this.newGame("friend", fen
);
509 domProps: { innerHTML: "Ok" },
516 document
.getElementById("input-fen").value
=
517 VariantRules
.GenRandInitFen();
520 domProps: { innerHTML: "Random" },
528 elementArray
= elementArray
.concat(modalFenEdit
);
529 const actions
= h('div',
531 attrs: { "id": "actions" },
532 'class': { 'text-center': true },
536 elementArray
.push(actions
);
537 if (this.score
!= "*")
541 { attrs: { id: "pgn-div" } },
553 attrs: { id: "pgn-game" },
554 on: { click: this.download
},
555 domProps: { innerHTML: this.pgnTxt
}
562 else if (this.mode
!= "idle")
567 { attrs: { id: "fen-div" } },
571 attrs: { id: "fen-string" },
572 domProps: { innerHTML: this.vr
.getFen() }
585 "col-md-offset-2":true,
587 "col-lg-offset-3":true,
589 // NOTE: click = mousedown + mouseup
591 mousedown: this.mousedown
,
592 mousemove: this.mousemove
,
593 mouseup: this.mouseup
,
594 touchstart: this.mousedown
,
595 touchmove: this.mousemove
,
596 touchend: this.mouseup
,
602 created: function() {
603 const url
= socketUrl
;
604 const continuation
= (localStorage
.getItem("variant") === variant
);
605 this.myid
= continuation
? localStorage
.getItem("myid") : getRandString();
608 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
609 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
611 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
612 const socketOpenListener
= () => {
615 const fen
= localStorage
.getItem("fen");
616 const mycolor
= localStorage
.getItem("mycolor");
617 const oppid
= localStorage
.getItem("oppid");
618 const moves
= JSON
.parse(localStorage
.getItem("moves"));
619 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
620 // Send ping to server (answer pong if opponent is connected)
621 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
623 else if (localStorage
.getItem("newgame") === variant
)
625 // New game request has been cancelled on disconnect
626 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
629 const socketMessageListener
= msg
=> {
630 const data
= JSON
.parse(msg
.data
);
633 case "newgame": //opponent found
634 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
636 case "newmove": //..he played!
637 this.play(data
.move, "animate");
639 case "pong": //received if we sent a ping (game still alive on our side)
640 this.oppConnected
= true;
641 const L
= this.vr
.moves
.length
;
642 // Send our "last state" informations to opponent
643 this.conn
.send(JSON
.stringify({
646 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
650 case "lastate": //got opponent infos about last move (we might have resigned)
651 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
654 this.conn
.send(JSON
.stringify({
661 else if (data
.movesCount
< 0)
664 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
666 else if (data
.movesCount
< this.vr
.moves
.length
)
668 // We must tell last move to opponent
669 const L
= this.vr
.moves
.length
;
670 this.conn
.send(JSON
.stringify({
673 lastMove:this.vr
.moves
[L
-1],
677 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
678 this.play(data
.lastMove
, "animate");
680 case "resign": //..you won!
681 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
683 // TODO: also use (dis)connect info to count online players?
686 if (this.mode
== "human" && this.oppid
== data
.id
)
687 this.oppConnected
= (data
.code
== "connect");
691 const socketCloseListener
= () => {
692 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
693 this.conn
.addEventListener('open', socketOpenListener
);
694 this.conn
.addEventListener('message', socketMessageListener
);
695 this.conn
.addEventListener('close', socketCloseListener
);
697 this.conn
.onopen
= socketOpenListener
;
698 this.conn
.onmessage
= socketMessageListener
;
699 this.conn
.onclose
= socketCloseListener
;
700 // Listen to keyboard left/right to navigate in game
701 document
.onkeydown
= event
=> {
702 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
703 && [37,39].includes(event
.keyCode
))
705 event
.preventDefault();
706 if (event
.keyCode
== 37) //Back
714 download: function() {
715 let content
= document
.getElementById("pgn-game").innerHTML
;
716 content
= content
.replace(/<br>/g, "\n");
717 // Prepare and trigger download link
718 let downloadAnchor
= document
.getElementById("download");
719 downloadAnchor
.setAttribute("download", "game.pgn");
720 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
721 downloadAnchor
.click();
723 endGame: function(score
) {
725 let modalBox
= document
.getElementById("modal-eog");
726 modalBox
.checked
= true;
727 // Variants may have special PGN structure (so next function isn't defined here)
728 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
729 setTimeout(() => { modalBox
.checked
= false; }, 2000);
730 if (this.mode
== "human")
733 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
736 getEndgameMessage: function(score
) {
737 let eogMessage
= "Unfinished";
741 eogMessage
= "White win";
744 eogMessage
= "Black win";
752 setStorage: function() {
753 localStorage
.setItem("myid", this.myid
);
754 localStorage
.setItem("variant", variant
);
755 localStorage
.setItem("mycolor", this.mycolor
);
756 localStorage
.setItem("oppid", this.oppid
);
757 localStorage
.setItem("fenStart", this.fenStart
);
758 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
759 localStorage
.setItem("fen", this.vr
.getFen());
761 updateStorage: function() {
762 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
763 localStorage
.setItem("fen", this.vr
.getFen());
765 clearStorage: function() {
766 delete localStorage
["variant"];
767 delete localStorage
["myid"];
768 delete localStorage
["mycolor"];
769 delete localStorage
["oppid"];
770 delete localStorage
["fenStart"];
771 delete localStorage
["fen"];
772 delete localStorage
["moves"];
774 // HACK because mini-css tooltips are persistent after click...
775 getRidOfTooltip: function(elt
) {
776 elt
.style
.visibility
= "hidden";
777 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
779 clickGameSeek: function(e
) {
780 this.getRidOfTooltip(e
.currentTarget
);
781 if (this.mode
== "human")
782 return; //no newgame while playing
785 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
786 delete localStorage
["newgame"]; //cancel game seek
790 this.newGame("human");
792 clickComputerGame: function(e
) {
793 this.getRidOfTooltip(e
.currentTarget
);
794 if (this.mode
== "human")
795 return; //no newgame while playing
796 this.newGame("computer");
798 clickFriendGame: function(e
) {
799 this.getRidOfTooltip(e
.currentTarget
);
800 document
.getElementById("modal-fenedit").checked
= true;
802 toggleExpertMode: function(e
) {
803 this.getRidOfTooltip(e
.currentTarget
);
804 this.expert
= !this.expert
;
805 setCookie("expert", this.expert
? "1" : "0");
807 resign: function(e
) {
808 this.getRidOfTooltip(e
.currentTarget
);
809 if (this.mode
== "human" && this.oppConnected
)
812 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
813 } catch (INVALID_STATE_ERR
) {
814 return; //socket is not ready (and not yet reconnected)
817 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
819 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
820 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
821 console
.log(fen
); //DEBUG
822 if (mode
=="human" && !oppId
)
824 const storageVariant
= localStorage
.getItem("variant");
825 if (!!storageVariant
&& storageVariant
!== variant
)
827 alert("Finish your " + storageVariant
+ " game first!");
830 // Send game request and wait..
831 localStorage
["newgame"] = variant
;
833 this.clearStorage(); //in case of
835 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
836 } catch (INVALID_STATE_ERR
) {
837 return; //nothing achieved
839 if (continuation
!== "reconnect") //TODO: bad HACK...
841 let modalBox
= document
.getElementById("modal-newgame");
842 modalBox
.checked
= true;
843 setTimeout(() => { modalBox
.checked
= false; }, 2000);
847 this.gameId
= getRandString();
848 this.vr
= new VariantRules(fen
, moves
|| []);
850 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
852 this.incheck
= []; //in case of
853 this.fenStart
= (continuation
? localStorage
.getItem("fenStart") : fen
);
859 // Not playing sound on game continuation:
860 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
861 document
.getElementById("modal-newgame").checked
= false;
864 this.oppConnected
= true;
865 this.mycolor
= color
;
867 if (!!moves
&& moves
.length
> 0) //imply continuation
869 const lastMove
= moves
[moves
.length
-1];
870 this.vr
.undo(lastMove
);
871 this.incheck
= this.vr
.getCheckSquares(lastMove
);
872 this.vr
.play(lastMove
, "ingame");
874 delete localStorage
["newgame"];
875 this.setStorage(); //in case of interruptions
877 else if (mode
== "computer")
879 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
880 if (this.mycolor
== 'b')
881 setTimeout(this.playComputerMove
, 500);
883 //else: against a (IRL) friend: nothing more to do
885 playComputerMove: function() {
886 const timeStart
= Date
.now();
887 const nbMoves
= this.vr
.moves
.length
; //using played moves to know if search finished
888 const gameId
= this.gameId
; //to know if game was reset before timer end
891 if (gameId
!= this.gameId
)
892 return; //game stopped
893 const L
= this.vr
.moves
.length
;
894 if (nbMoves
== L
|| !this.vr
.moves
[L
-1].notation
) //move search didn't finish
895 this.vr
.shouldReturn
= true;
897 const compMove
= this.vr
.getComputerMove();
898 // (first move) HACK: avoid selecting elements before they appear on page:
899 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
900 setTimeout(() => this.play(compMove
, "animate"), delay
);
902 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
903 getSquareId: function(o
) {
904 // NOTE: a separator is required to allow any size of board
905 return "sq-" + o
.x
+ "-" + o
.y
;
908 getSquareFromId: function(id
) {
909 let idParts
= id
.split('-');
910 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
912 mousedown: function(e
) {
913 e
= e
|| window
.event
;
916 while (!ingame
&& elem
!== null)
918 if (elem
.classList
.contains("game"))
923 elem
= elem
.parentElement
;
925 if (!ingame
) //let default behavior (click on button...)
927 e
.preventDefault(); //disable native drag & drop
928 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
930 // Next few lines to center the piece on mouse cursor
931 let rect
= e
.target
.parentNode
.getBoundingClientRect();
933 x: rect
.x
+ rect
.width
/2,
934 y: rect
.y
+ rect
.width
/2,
935 id: e
.target
.parentNode
.id
937 this.selectedPiece
= e
.target
.cloneNode();
938 this.selectedPiece
.style
.position
= "absolute";
939 this.selectedPiece
.style
.top
= 0;
940 this.selectedPiece
.style
.display
= "inline-block";
941 this.selectedPiece
.style
.zIndex
= 3000;
942 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
943 const iCanPlay
= this.mode
!="idle"
944 && (this.mode
=="friend" || this.vr
.canIplay(this.mycolor
,startSquare
));
945 this.possibleMoves
= iCanPlay
? this.vr
.getPossibleMovesFrom(startSquare
) : [];
946 // Next line add moving piece just after current image (required for Crazyhouse reserve)
947 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
950 mousemove: function(e
) {
951 if (!this.selectedPiece
)
953 e
= e
|| window
.event
;
954 // If there is an active element, move it around
955 if (!!this.selectedPiece
)
957 const [offsetX
,offsetY
] = !!e
.clientX
958 ? [e
.clientX
,e
.clientY
] //desktop browser
959 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
960 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
961 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
964 mouseup: function(e
) {
965 if (!this.selectedPiece
)
967 e
= e
|| window
.event
;
968 // Read drop target (or parentElement, parentNode... if type == "img")
969 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
970 const [offsetX
,offsetY
] = !!e
.clientX
971 ? [e
.clientX
,e
.clientY
]
972 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
973 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
974 this.selectedPiece
.style
.zIndex
= 3000;
975 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
976 landing
= landing
.parentNode
;
977 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
979 // OK: process move attempt
980 let endSquare
= this.getSquareFromId(landing
.id
);
981 let moves
= this.findMatchingMoves(endSquare
);
982 this.possibleMoves
= [];
983 if (moves
.length
> 1)
984 this.choices
= moves
;
985 else if (moves
.length
==1)
987 // Else: impossible move
988 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
989 delete this.selectedPiece
;
990 this.selectedPiece
= null;
992 findMatchingMoves: function(endSquare
) {
993 // Run through moves list and return the matching set (if promotions...)
995 this.possibleMoves
.forEach(function(m
) {
996 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1001 animateMove: function(move) {
1002 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1003 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1004 let rectStart
= startSquare
.getBoundingClientRect();
1005 let rectEnd
= endSquare
.getBoundingClientRect();
1006 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1008 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1009 // HACK for animation (with positive translate, image slides "under background"...)
1010 // Possible improvement: just alter squares on the piece's way...
1011 squares
= document
.getElementsByClassName("board");
1012 for (let i
=0; i
<squares
.length
; i
++)
1014 let square
= squares
.item(i
);
1015 if (square
.id
!= this.getSquareId(move.start
))
1016 square
.style
.zIndex
= "-1";
1018 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
1019 movingPiece
.style
.transitionDuration
= "0.2s";
1020 movingPiece
.style
.zIndex
= "3000";
1022 for (let i
=0; i
<squares
.length
; i
++)
1023 squares
.item(i
).style
.zIndex
= "auto";
1024 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1028 play: function(move, programmatic
) {
1031 // Navigate after game is over
1032 if (this.cursor
>= this.vr
.moves
.length
)
1033 return; //already at the end
1034 move = this.vr
.moves
[this.cursor
++];
1036 if (!!programmatic
) //computer or human opponent
1038 this.animateMove(move);
1041 // Not programmatic, or animation is over
1042 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1043 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1044 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
1045 if (this.mode
!= "idle")
1047 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1048 this.vr
.play(move, "ingame");
1052 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1053 this.$forceUpdate(); //TODO: ?!
1055 if (this.mode
== "human")
1056 this.updateStorage(); //after our moves and opponent moves
1057 if (this.mode
!= "idle")
1059 const eog
= this.vr
.checkGameOver();
1063 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1064 setTimeout(this.playComputerMove
, 500);
1067 // Navigate after game is over
1068 if (this.cursor
== 0)
1069 return; //already at the beginning
1070 if (this.cursor
== this.vr
.moves
.length
)
1071 this.incheck
= []; //in case of...
1072 const move = this.vr
.moves
[--this.cursor
];
1073 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1074 this.$forceUpdate(); //TODO: ?!
1076 undoInGame: function() {
1077 const lm
= this.vr
.lastMove
;