2da7ad050f2f92dfb1ed7f3de3eac5bb6cc35a31
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
<= 500);
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' },
132 "topindicator": true,
134 "expert-switch": true,
135 "expert-mode": this.expert
,
136 "small": smallScreen
,
139 [h('i', { 'class': { "material-icons": true } }, "visibility_off")]
141 elementArray
.push(expertSwitch
);
142 let choices
= h('div',
144 attrs: { "id": "choices" },
145 'class': { 'row': true },
147 "display": this.choices
.length
>0?"block":"none",
148 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
149 "width": (this.choices
.length
* squareWidth
) + "px",
150 "height": squareWidth
+ "px",
153 this.choices
.map( m
=> { //a "choice" is a move
158 ['board'+sizeY
]: true,
161 'width': (100/this.choices
.length
) + "%",
162 'padding-bottom': (100/this.choices
.length
) + "%",
167 attrs: { "src": '/images/pieces/' +
168 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
169 'class': { 'choice-piece': true },
170 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
176 // Create board element (+ reserves if needed by variant or mode)
177 let gameDiv
= h('div',
179 'class': { 'game': true },
181 [_
.range(sizeX
).map(i
=> {
182 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
189 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
191 _
.range(sizeY
).map(j
=> {
192 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
194 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
202 'ghost': !!this.selectedPiece
203 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
206 src: "/images/pieces/" +
207 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
213 if (!this.expert
&& hintSquares
[ci
][cj
])
223 src: "/images/mark.svg",
229 const lm
= this.vr
.lastMove
;
230 const showLight
= !this.expert
&&
231 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
237 ['board'+sizeY
]: true,
238 'light-square': (i
+j
)%2==0,
239 'dark-square': (i
+j
)%2==1,
240 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
241 'incheck': showLight
&& incheckSq
[ci
][cj
],
244 id: this.getSquareId({x:ci
,y:cj
}),
253 if (this.mode
!= "idle")
258 on: { click: this.resign
},
259 attrs: { "aria-label": 'Resign' },
263 "small": smallScreen
,
266 [h('i', { 'class': { "material-icons": true } }, "flag")])
269 else if (this.vr
.moves
.length
> 0)
271 // A game finished, and another is not started yet: allow navigation
272 actionArray
= actionArray
.concat([
275 style: { "margin-left": "30px" },
276 on: { click: e
=> this.undo() },
277 attrs: { "aria-label": 'Undo' },
278 "class": { "small": smallScreen
},
280 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
283 on: { click: e
=> this.play() },
284 attrs: { "aria-label": 'Play' },
285 "class": { "small": smallScreen
},
287 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
291 if (this.mode
== "friend")
293 actionArray
= actionArray
.concat(
297 style: { "margin-left": "30px" },
298 on: { click: this.undoInGame
},
299 attrs: { "aria-label": 'Undo' },
300 "class": { "small": smallScreen
},
302 [h('i', { 'class': { "material-icons": true } }, "undo")]
306 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
307 attrs: { "aria-label": 'Flip' },
308 "class": { "small": smallScreen
},
310 [h('i', { 'class': { "material-icons": true } }, "cached")]
314 elementArray
.push(gameDiv
);
315 if (!!this.vr
.reserve
)
317 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
318 let myReservePiecesArray
= [];
319 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
321 myReservePiecesArray
.push(h('div',
323 'class': {'board':true, ['board'+sizeY
]:true},
324 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
329 'class': {"piece":true},
331 "src": "/images/pieces/" +
332 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
336 {style: { "padding-left":"40%"} },
337 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
341 let oppReservePiecesArray
= [];
342 const oppCol
= this.vr
.getOppCol(this.mycolor
);
343 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
345 oppReservePiecesArray
.push(h('div',
347 'class': {'board':true, ['board'+sizeY
]:true},
348 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
353 'class': {"piece":true},
355 "src": "/images/pieces/" +
356 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
360 {style: { "padding-left":"40%"} },
361 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
365 let reserves
= h('div',
367 'class':{'game':true},
368 style: {"margin-bottom": "20px"},
373 'class': { 'row': true },
374 style: {"margin-bottom": "15px"},
379 { 'class': { 'row': true }},
380 oppReservePiecesArray
384 elementArray
.push(reserves
);
386 const eogMessage
= this.getEndgameMessage(this.score
);
390 attrs: { "id": "modal-eog", type: "checkbox" },
391 "class": { "modal": true },
395 attrs: { "role": "dialog", "aria-labelledby": "modal-eog" },
400 "class": { "card": true, "smallpad": true },
405 attrs: { "for": "modal-eog" },
406 "class": { "modal-close": true },
411 "class": { "section": true },
412 domProps: { innerHTML: eogMessage
},
420 elementArray
= elementArray
.concat(modalEog
);
422 const modalNewgame
= [
425 attrs: { "id": "modal-newgame", type: "checkbox" },
426 "class": { "modal": true },
430 attrs: { "role": "dialog", "aria-labelledby": "modal-newgame" },
435 "class": { "card": true, "smallpad": true },
440 attrs: { "id": "close-newgame", "for": "modal-newgame" },
441 "class": { "modal-close": true },
446 "class": { "section": true },
447 domProps: { innerHTML: "New game" },
452 "class": { "section": true },
453 domProps: { innerHTML: "Waiting for opponent..." },
461 elementArray
= elementArray
.concat(modalNewgame
);
462 const modalFenEdit
= [
465 attrs: { "id": "modal-fenedit", type: "checkbox" },
466 "class": { "modal": true },
470 attrs: { "role": "dialog", "aria-labelledby": "modal-fenedit" },
475 "class": { "card": true, "smallpad": true },
480 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
481 "class": { "modal-close": true },
486 "class": { "section": true },
487 domProps: { innerHTML: "Position + flags (FEN):" },
495 value: VariantRules
.GenRandInitFen(),
503 const fen
= document
.getElementById("input-fen").value
;
504 document
.getElementById("modal-fenedit").checked
= false;
505 this.newGame("friend", fen
);
508 domProps: { innerHTML: "Ok" },
515 document
.getElementById("input-fen").value
=
516 VariantRules
.GenRandInitFen();
519 domProps: { innerHTML: "Random" },
527 elementArray
= elementArray
.concat(modalFenEdit
);
528 const actions
= h('div',
530 attrs: { "id": "actions" },
531 'class': { 'text-center': true },
535 elementArray
.push(actions
);
536 if (this.score
!= "*")
540 { attrs: { id: "pgn-div" } },
552 attrs: { id: "pgn-game" },
553 on: { click: this.download
},
554 domProps: { innerHTML: this.pgnTxt
}
561 else if (this.mode
!= "idle")
566 { attrs: { id: "fen-div" } },
570 attrs: { id: "fen-string" },
571 domProps: { innerHTML: this.vr
.getFen() }
584 "col-md-offset-2":true,
586 "col-lg-offset-3":true,
588 // NOTE: click = mousedown + mouseup
590 mousedown: this.mousedown
,
591 mousemove: this.mousemove
,
592 mouseup: this.mouseup
,
593 touchstart: this.mousedown
,
594 touchmove: this.mousemove
,
595 touchend: this.mouseup
,
601 created: function() {
602 const url
= socketUrl
;
603 const continuation
= (localStorage
.getItem("variant") === variant
);
604 this.myid
= continuation
? localStorage
.getItem("myid") : getRandString();
607 // HACK: play a small silent sound to allow "new game" sound later if tab not focused
608 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
610 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
611 const socketOpenListener
= () => {
614 const fen
= localStorage
.getItem("fen");
615 const mycolor
= localStorage
.getItem("mycolor");
616 const oppid
= localStorage
.getItem("oppid");
617 const moves
= JSON
.parse(localStorage
.getItem("moves"));
618 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
619 // Send ping to server (answer pong if opponent is connected)
620 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
622 else if (localStorage
.getItem("newgame") === variant
)
624 // New game request has been cancelled on disconnect
625 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
628 const socketMessageListener
= msg
=> {
629 const data
= JSON
.parse(msg
.data
);
632 case "newgame": //opponent found
633 this.newGame("human", data
.fen
, data
.color
, data
.oppid
); //oppid: opponent socket ID
635 case "newmove": //..he played!
636 this.play(data
.move, "animate");
638 case "pong": //received if we sent a ping (game still alive on our side)
639 this.oppConnected
= true;
640 const L
= this.vr
.moves
.length
;
641 // Send our "last state" informations to opponent
642 this.conn
.send(JSON
.stringify({
645 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
649 case "lastate": //got opponent infos about last move (we might have resigned)
650 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
653 this.conn
.send(JSON
.stringify({
660 else if (data
.movesCount
< 0)
663 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
665 else if (data
.movesCount
< this.vr
.moves
.length
)
667 // We must tell last move to opponent
668 const L
= this.vr
.moves
.length
;
669 this.conn
.send(JSON
.stringify({
672 lastMove:this.vr
.moves
[L
-1],
676 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
677 this.play(data
.lastMove
, "animate");
679 case "resign": //..you won!
680 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
682 // TODO: also use (dis)connect info to count online players?
685 if (this.mode
== "human" && this.oppid
== data
.id
)
686 this.oppConnected
= (data
.code
== "connect");
690 const socketCloseListener
= () => {
691 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
692 this.conn
.addEventListener('open', socketOpenListener
);
693 this.conn
.addEventListener('message', socketMessageListener
);
694 this.conn
.addEventListener('close', socketCloseListener
);
696 this.conn
.onopen
= socketOpenListener
;
697 this.conn
.onmessage
= socketMessageListener
;
698 this.conn
.onclose
= socketCloseListener
;
699 // Listen to keyboard left/right to navigate in game
700 document
.onkeydown
= event
=> {
701 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
702 && [37,39].includes(event
.keyCode
))
704 event
.preventDefault();
705 if (event
.keyCode
== 37) //Back
713 download: function() {
714 let content
= document
.getElementById("pgn-game").innerHTML
;
715 content
= content
.replace(/<br>/g, "\n");
716 // Prepare and trigger download link
717 let downloadAnchor
= document
.getElementById("download");
718 downloadAnchor
.setAttribute("download", "game.pgn");
719 downloadAnchor
.href
= "data:text/plain;charset=utf-8," + encodeURIComponent(content
);
720 downloadAnchor
.click();
722 endGame: function(score
) {
724 let modalBox
= document
.getElementById("modal-eog");
725 modalBox
.checked
= true;
726 // Variants may have special PGN structure (so next function isn't defined here)
727 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
728 setTimeout(() => { modalBox
.checked
= false; }, 2000);
729 if (this.mode
== "human")
732 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
735 getEndgameMessage: function(score
) {
736 let eogMessage
= "Unfinished";
740 eogMessage
= "White win";
743 eogMessage
= "Black win";
751 setStorage: function() {
752 localStorage
.setItem("myid", this.myid
);
753 localStorage
.setItem("variant", variant
);
754 localStorage
.setItem("mycolor", this.mycolor
);
755 localStorage
.setItem("oppid", this.oppid
);
756 localStorage
.setItem("fenStart", this.fenStart
);
757 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
758 localStorage
.setItem("fen", this.vr
.getFen());
760 updateStorage: function() {
761 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
762 localStorage
.setItem("fen", this.vr
.getFen());
764 clearStorage: function() {
765 delete localStorage
["variant"];
766 delete localStorage
["myid"];
767 delete localStorage
["mycolor"];
768 delete localStorage
["oppid"];
769 delete localStorage
["fenStart"];
770 delete localStorage
["fen"];
771 delete localStorage
["moves"];
773 // HACK because mini-css tooltips are persistent after click...
774 getRidOfTooltip: function(elt
) {
775 elt
.style
.visibility
= "hidden";
776 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
778 clickGameSeek: function(e
) {
779 this.getRidOfTooltip(e
.currentTarget
);
780 if (this.mode
== "human")
781 return; //no newgame while playing
784 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
785 delete localStorage
["newgame"]; //cancel game seek
789 this.newGame("human");
791 clickComputerGame: function(e
) {
792 this.getRidOfTooltip(e
.currentTarget
);
793 if (this.mode
== "human")
794 return; //no newgame while playing
795 this.newGame("computer");
797 clickFriendGame: function(e
) {
798 this.getRidOfTooltip(e
.currentTarget
);
799 document
.getElementById("modal-fenedit").checked
= true;
801 toggleExpertMode: function(e
) {
802 this.getRidOfTooltip(e
.currentTarget
);
803 this.expert
= !this.expert
;
804 setCookie("expert", this.expert
? "1" : "0");
806 resign: function(e
) {
807 this.getRidOfTooltip(e
.currentTarget
);
808 if (this.mode
== "human" && this.oppConnected
)
811 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
812 } catch (INVALID_STATE_ERR
) {
813 return; //socket is not ready (and not yet reconnected)
816 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
818 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
819 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
820 console
.log(fen
); //DEBUG
821 if (mode
=="human" && !oppId
)
823 const storageVariant
= localStorage
.getItem("variant");
824 if (!!storageVariant
&& storageVariant
!== variant
)
826 alert("Finish your " + storageVariant
+ " game first!");
829 // Send game request and wait..
830 localStorage
["newgame"] = variant
;
832 this.clearStorage(); //in case of
834 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
835 } catch (INVALID_STATE_ERR
) {
836 return; //nothing achieved
838 if (continuation
!== "reconnect") //TODO: bad HACK...
840 let modalBox
= document
.getElementById("modal-newgame");
841 modalBox
.checked
= true;
842 setTimeout(() => { modalBox
.checked
= false; }, 2000);
846 this.gameId
= getRandString();
847 this.vr
= new VariantRules(fen
, moves
|| []);
849 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
851 this.incheck
= []; //in case of
852 this.fenStart
= (continuation
? localStorage
.getItem("fenStart") : fen
);
858 // Not playing sound on game continuation:
859 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
860 document
.getElementById("modal-newgame").checked
= false;
863 this.oppConnected
= true;
864 this.mycolor
= color
;
866 if (!!moves
&& moves
.length
> 0) //imply continuation
868 const lastMove
= moves
[moves
.length
-1];
869 this.vr
.undo(lastMove
);
870 this.incheck
= this.vr
.getCheckSquares(lastMove
);
871 this.vr
.play(lastMove
, "ingame");
873 delete localStorage
["newgame"];
874 this.setStorage(); //in case of interruptions
876 else if (mode
== "computer")
878 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
879 if (this.mycolor
== 'b')
880 setTimeout(this.playComputerMove
, 500);
882 //else: against a (IRL) friend: nothing more to do
884 playComputerMove: function() {
885 const timeStart
= Date
.now();
886 const nbMoves
= this.vr
.moves
.length
; //using played moves to know if search finished
887 const gameId
= this.gameId
; //to know if game was reset before timer end
890 if (gameId
!= this.gameId
)
891 return; //game stopped
892 const L
= this.vr
.moves
.length
;
893 if (nbMoves
== L
|| !this.vr
.moves
[L
-1].notation
) //move search didn't finish
894 this.vr
.shouldReturn
= true;
896 const compMove
= this.vr
.getComputerMove();
897 // (first move) HACK: avoid selecting elements before they appear on page:
898 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
899 setTimeout(() => this.play(compMove
, "animate"), delay
);
901 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
902 getSquareId: function(o
) {
903 // NOTE: a separator is required to allow any size of board
904 return "sq-" + o
.x
+ "-" + o
.y
;
907 getSquareFromId: function(id
) {
908 let idParts
= id
.split('-');
909 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
911 mousedown: function(e
) {
912 e
= e
|| window
.event
;
915 while (!ingame
&& elem
!== null)
917 if (elem
.classList
.contains("game"))
922 elem
= elem
.parentElement
;
924 if (!ingame
) //let default behavior (click on button...)
926 e
.preventDefault(); //disable native drag & drop
927 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
929 // Next few lines to center the piece on mouse cursor
930 let rect
= e
.target
.parentNode
.getBoundingClientRect();
932 x: rect
.x
+ rect
.width
/2,
933 y: rect
.y
+ rect
.width
/2,
934 id: e
.target
.parentNode
.id
936 this.selectedPiece
= e
.target
.cloneNode();
937 this.selectedPiece
.style
.position
= "absolute";
938 this.selectedPiece
.style
.top
= 0;
939 this.selectedPiece
.style
.display
= "inline-block";
940 this.selectedPiece
.style
.zIndex
= 3000;
941 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
942 const iCanPlay
= this.mode
!="idle"
943 && (this.mode
=="friend" || this.vr
.canIplay(this.mycolor
,startSquare
));
944 this.possibleMoves
= iCanPlay
? this.vr
.getPossibleMovesFrom(startSquare
) : [];
945 // Next line add moving piece just after current image (required for Crazyhouse reserve)
946 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
949 mousemove: function(e
) {
950 if (!this.selectedPiece
)
952 e
= e
|| window
.event
;
953 // If there is an active element, move it around
954 if (!!this.selectedPiece
)
956 const [offsetX
,offsetY
] = !!e
.clientX
957 ? [e
.clientX
,e
.clientY
] //desktop browser
958 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
959 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
960 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
963 mouseup: function(e
) {
964 if (!this.selectedPiece
)
966 e
= e
|| window
.event
;
967 // Read drop target (or parentElement, parentNode... if type == "img")
968 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coordinates
969 const [offsetX
,offsetY
] = !!e
.clientX
970 ? [e
.clientX
,e
.clientY
]
971 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
972 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
973 this.selectedPiece
.style
.zIndex
= 3000;
974 while (landing
.tagName
== "IMG") //classList.contains(piece) fails because of mark/highlight
975 landing
= landing
.parentNode
;
976 if (this.start
.id
== landing
.id
) //a click: selectedPiece and possibleMoves already filled
978 // OK: process move attempt
979 let endSquare
= this.getSquareFromId(landing
.id
);
980 let moves
= this.findMatchingMoves(endSquare
);
981 this.possibleMoves
= [];
982 if (moves
.length
> 1)
983 this.choices
= moves
;
984 else if (moves
.length
==1)
986 // Else: impossible move
987 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
988 delete this.selectedPiece
;
989 this.selectedPiece
= null;
991 findMatchingMoves: function(endSquare
) {
992 // Run through moves list and return the matching set (if promotions...)
994 this.possibleMoves
.forEach(function(m
) {
995 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1000 animateMove: function(move) {
1001 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1002 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1003 let rectStart
= startSquare
.getBoundingClientRect();
1004 let rectEnd
= endSquare
.getBoundingClientRect();
1005 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1007 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1008 // HACK for animation (with positive translate, image slides "under background"...)
1009 // Possible improvement: just alter squares on the piece's way...
1010 squares
= document
.getElementsByClassName("board");
1011 for (let i
=0; i
<squares
.length
; i
++)
1013 let square
= squares
.item(i
);
1014 if (square
.id
!= this.getSquareId(move.start
))
1015 square
.style
.zIndex
= "-1";
1017 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," + translation
.y
+ "px)";
1018 movingPiece
.style
.transitionDuration
= "0.2s";
1019 movingPiece
.style
.zIndex
= "3000";
1021 for (let i
=0; i
<squares
.length
; i
++)
1022 squares
.item(i
).style
.zIndex
= "auto";
1023 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1027 play: function(move, programmatic
) {
1030 // Navigate after game is over
1031 if (this.cursor
>= this.vr
.moves
.length
)
1032 return; //already at the end
1033 move = this.vr
.moves
[this.cursor
++];
1035 if (!!programmatic
) //computer or human opponent
1037 this.animateMove(move);
1040 // Not programmatic, or animation is over
1041 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1042 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1043 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
1044 if (this.mode
!= "idle")
1046 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1047 this.vr
.play(move, "ingame");
1051 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1052 this.$forceUpdate(); //TODO: ?!
1054 if (this.mode
== "human")
1055 this.updateStorage(); //after our moves and opponent moves
1056 if (this.mode
!= "idle")
1058 const eog
= this.vr
.checkGameOver();
1062 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1063 setTimeout(this.playComputerMove
, 500);
1066 // Navigate after game is over
1067 if (this.cursor
== 0)
1068 return; //already at the beginning
1069 if (this.cursor
== this.vr
.moves
.length
)
1070 this.incheck
= []; //in case of...
1071 const move = this.vr
.moves
[--this.cursor
];
1072 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1073 this.$forceUpdate(); //TODO: ?!
1075 undoInGame: function() {
1076 const lm
= this.vr
.lastMove
;