1 // Game logic on a variant page
2 Vue
.component('my-game', {
5 vr: null, //object to check moves, store them, FEN..
7 possibleMoves: [], //filled after each valid click/dragstart
8 choices: [], //promotion pieces, or checkered captures... (as moves)
9 start: {}, //pixels coordinates + id of starting square (click or drag)
10 selectedPiece: null, //moving piece (or clicked piece)
11 conn: null, //socket connection
12 score: "*", //'*' means 'unfinished'
13 mode: "idle", //human, friend, computer or idle (when not playing)
14 oppid: "", //opponent ID in case of HH game
20 expert: (getCookie("expert") === "1" ? true : false),
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' },
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 on: { click: e
=> this.undo() },
276 attrs: { "aria-label": 'Undo' },
278 "small": smallScreen
,
282 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
285 on: { click: e
=> this.play() },
286 attrs: { "aria-label": 'Play' },
287 "class": { "small": smallScreen
},
289 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
293 if (this.mode
== "friend")
295 actionArray
= actionArray
.concat(
299 on: { click: this.undoInGame
},
300 attrs: { "aria-label": 'Undo' },
302 "small": smallScreen
,
306 [h('i', { 'class': { "material-icons": true } }, "undo")]
310 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
311 attrs: { "aria-label": 'Flip' },
312 "class": { "small": smallScreen
},
314 [h('i', { 'class': { "material-icons": true } }, "cached")]
318 elementArray
.push(gameDiv
);
319 if (!!this.vr
.reserve
)
321 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
322 let myReservePiecesArray
= [];
323 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
325 myReservePiecesArray
.push(h('div',
327 'class': {'board':true, ['board'+sizeY
]:true},
328 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
333 'class': {"piece":true},
335 "src": "/images/pieces/" +
336 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
340 {"class": { "reserve-count": true } },
341 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
345 let oppReservePiecesArray
= [];
346 const oppCol
= this.vr
.getOppCol(this.mycolor
);
347 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
349 oppReservePiecesArray
.push(h('div',
351 'class': {'board':true, ['board'+sizeY
]:true},
352 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
357 'class': {"piece":true},
359 "src": "/images/pieces/" +
360 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
364 {"class": { "reserve-count": true } },
365 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
369 let reserves
= h('div',
381 "reserve-row-1": true,
387 { 'class': { 'row': true }},
388 oppReservePiecesArray
392 elementArray
.push(reserves
);
394 const eogMessage
= this.getEndgameMessage(this.score
);
398 attrs: { "id": "modal-eog", type: "checkbox" },
399 "class": { "modal": true },
403 attrs: { "role": "dialog", "aria-labelledby": "modal-eog" },
408 "class": { "card": true, "smallpad": true },
413 attrs: { "for": "modal-eog" },
414 "class": { "modal-close": true },
419 "class": { "section": true },
420 domProps: { innerHTML: eogMessage
},
428 elementArray
= elementArray
.concat(modalEog
);
430 const modalNewgame
= [
433 attrs: { "id": "modal-newgame", type: "checkbox" },
434 "class": { "modal": true },
438 attrs: { "role": "dialog", "aria-labelledby": "modal-newgame" },
443 "class": { "card": true, "smallpad": true },
448 attrs: { "id": "close-newgame", "for": "modal-newgame" },
449 "class": { "modal-close": true },
454 "class": { "section": true },
455 domProps: { innerHTML: "New game" },
460 "class": { "section": true },
461 domProps: { innerHTML: "Waiting for opponent..." },
469 elementArray
= elementArray
.concat(modalNewgame
);
470 const modalFenEdit
= [
473 attrs: { "id": "modal-fenedit", type: "checkbox" },
474 "class": { "modal": true },
478 attrs: { "role": "dialog", "aria-labelledby": "modal-fenedit" },
483 "class": { "card": true, "smallpad": true },
488 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
489 "class": { "modal-close": true },
494 "class": { "section": true },
495 domProps: { innerHTML: "Position + flags (FEN):" },
503 value: VariantRules
.GenRandInitFen(),
511 const fen
= document
.getElementById("input-fen").value
;
512 document
.getElementById("modal-fenedit").checked
= false;
513 this.newGame("friend", fen
);
516 domProps: { innerHTML: "Ok" },
523 document
.getElementById("input-fen").value
=
524 VariantRules
.GenRandInitFen();
527 domProps: { innerHTML: "Random" },
535 elementArray
= elementArray
.concat(modalFenEdit
);
536 const actions
= h('div',
538 attrs: { "id": "actions" },
539 'class': { 'text-center': true },
543 elementArray
.push(actions
);
544 if (this.score
!= "*")
548 { attrs: { id: "pgn-div" } },
560 attrs: { id: "pgn-game" },
561 on: { click: this.download
},
562 domProps: { innerHTML: this.pgnTxt
}
569 else if (this.mode
!= "idle")
574 { attrs: { id: "fen-div" } },
578 attrs: { id: "fen-string" },
579 domProps: { innerHTML: this.vr
.getFen() }
592 "col-md-offset-2":true,
594 "col-lg-offset-3":true,
596 // NOTE: click = mousedown + mouseup
598 mousedown: this.mousedown
,
599 mousemove: this.mousemove
,
600 mouseup: this.mouseup
,
601 touchstart: this.mousedown
,
602 touchmove: this.mousemove
,
603 touchend: this.mouseup
,
609 created: function() {
610 const url
= socketUrl
;
611 const continuation
= (localStorage
.getItem("variant") === variant
);
612 this.myid
= continuation
? localStorage
.getItem("myid") : getRandString();
615 // HACK: play a small silent sound to allow "new game" sound later
616 // if tab not focused (TODO: does it really work ?!)
617 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
619 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
620 const socketOpenListener
= () => {
623 const fen
= localStorage
.getItem("fen");
624 const mycolor
= localStorage
.getItem("mycolor");
625 const oppid
= localStorage
.getItem("oppid");
626 const moves
= JSON
.parse(localStorage
.getItem("moves"));
627 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
628 // Send ping to server (answer pong if opponent is connected)
629 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
631 else if (localStorage
.getItem("newgame") === variant
)
633 // New game request has been cancelled on disconnect
634 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
637 const socketMessageListener
= msg
=> {
638 const data
= JSON
.parse(msg
.data
);
641 case "newgame": //opponent found
642 // oppid: opponent socket ID
643 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
645 case "newmove": //..he played!
646 this.play(data
.move, "animate");
648 case "pong": //received if we sent a ping (game still alive on our side)
649 this.oppConnected
= true;
650 const L
= this.vr
.moves
.length
;
651 // Send our "last state" informations to opponent
652 this.conn
.send(JSON
.stringify({
655 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
659 case "lastate": //got opponent infos about last move (we might have resigned)
660 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
663 this.conn
.send(JSON
.stringify({
670 else if (data
.movesCount
< 0)
673 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
675 else if (data
.movesCount
< this.vr
.moves
.length
)
677 // We must tell last move to opponent
678 const L
= this.vr
.moves
.length
;
679 this.conn
.send(JSON
.stringify({
682 lastMove:this.vr
.moves
[L
-1],
686 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
687 this.play(data
.lastMove
, "animate");
689 case "resign": //..you won!
690 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
692 // TODO: also use (dis)connect info to count online players?
695 if (this.mode
== "human" && this.oppid
== data
.id
)
696 this.oppConnected
= (data
.code
== "connect");
700 const socketCloseListener
= () => {
701 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
702 this.conn
.addEventListener('open', socketOpenListener
);
703 this.conn
.addEventListener('message', socketMessageListener
);
704 this.conn
.addEventListener('close', socketCloseListener
);
706 this.conn
.onopen
= socketOpenListener
;
707 this.conn
.onmessage
= socketMessageListener
;
708 this.conn
.onclose
= socketCloseListener
;
709 // Listen to keyboard left/right to navigate in game
710 document
.onkeydown
= event
=> {
711 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
712 && [37,39].includes(event
.keyCode
))
714 event
.preventDefault();
715 if (event
.keyCode
== 37) //Back
723 download: function() {
724 let content
= document
.getElementById("pgn-game").innerHTML
;
725 content
= content
.replace(/<br>/g, "\n");
726 // Prepare and trigger download link
727 let downloadAnchor
= document
.getElementById("download");
728 downloadAnchor
.setAttribute("download", "game.pgn");
729 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
730 encodeURIComponent(content
);
731 downloadAnchor
.click();
733 endGame: function(score
) {
735 let modalBox
= document
.getElementById("modal-eog");
736 modalBox
.checked
= true;
737 // Variants may have special PGN structure (so next function isn't defined here)
738 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
739 setTimeout(() => { modalBox
.checked
= false; }, 2000);
740 if (this.mode
== "human")
743 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
746 getEndgameMessage: function(score
) {
747 let eogMessage
= "Unfinished";
751 eogMessage
= "White win";
754 eogMessage
= "Black win";
762 setStorage: function() {
763 localStorage
.setItem("myid", this.myid
);
764 localStorage
.setItem("variant", variant
);
765 localStorage
.setItem("mycolor", this.mycolor
);
766 localStorage
.setItem("oppid", this.oppid
);
767 localStorage
.setItem("fenStart", this.fenStart
);
768 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
769 localStorage
.setItem("fen", this.vr
.getFen());
771 updateStorage: function() {
772 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
773 localStorage
.setItem("fen", this.vr
.getFen());
775 clearStorage: function() {
776 delete localStorage
["variant"];
777 delete localStorage
["myid"];
778 delete localStorage
["mycolor"];
779 delete localStorage
["oppid"];
780 delete localStorage
["fenStart"];
781 delete localStorage
["fen"];
782 delete localStorage
["moves"];
784 // HACK because mini-css tooltips are persistent after click...
785 getRidOfTooltip: function(elt
) {
786 elt
.style
.visibility
= "hidden";
787 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
789 clickGameSeek: function(e
) {
790 this.getRidOfTooltip(e
.currentTarget
);
791 if (this.mode
== "human")
792 return; //no newgame while playing
795 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
796 delete localStorage
["newgame"]; //cancel game seek
800 this.newGame("human");
802 clickComputerGame: function(e
) {
803 this.getRidOfTooltip(e
.currentTarget
);
804 if (this.mode
== "human")
805 return; //no newgame while playing
806 this.newGame("computer");
808 clickFriendGame: function(e
) {
809 this.getRidOfTooltip(e
.currentTarget
);
810 document
.getElementById("modal-fenedit").checked
= true;
812 toggleExpertMode: function(e
) {
813 this.getRidOfTooltip(e
.currentTarget
);
814 this.expert
= !this.expert
;
815 setCookie("expert", this.expert
? "1" : "0");
817 resign: function(e
) {
818 this.getRidOfTooltip(e
.currentTarget
);
819 if (this.mode
== "human" && this.oppConnected
)
822 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
823 } catch (INVALID_STATE_ERR
) {
824 return; //socket is not ready (and not yet reconnected)
827 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
829 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
830 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
831 console
.log(fen
); //DEBUG
832 if (mode
=="human" && !oppId
)
834 const storageVariant
= localStorage
.getItem("variant");
835 if (!!storageVariant
&& storageVariant
!== variant
)
837 alert("Finish your " + storageVariant
+ " game first!");
840 // Send game request and wait..
841 localStorage
["newgame"] = variant
;
843 this.clearStorage(); //in case of
845 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
846 } catch (INVALID_STATE_ERR
) {
847 return; //nothing achieved
849 if (continuation
!== "reconnect") //TODO: bad HACK...
851 let modalBox
= document
.getElementById("modal-newgame");
852 modalBox
.checked
= true;
853 setTimeout(() => { modalBox
.checked
= false; }, 2000);
857 this.vr
= new VariantRules(fen
, moves
|| []);
859 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
861 this.incheck
= []; //in case of
862 this.fenStart
= (continuation
? localStorage
.getItem("fenStart") : fen
);
868 // Not playing sound on game continuation:
869 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
870 document
.getElementById("modal-newgame").checked
= false;
873 this.oppConnected
= true;
874 this.mycolor
= color
;
876 if (!!moves
&& moves
.length
> 0) //imply continuation
878 const lastMove
= moves
[moves
.length
-1];
879 this.vr
.undo(lastMove
);
880 this.incheck
= this.vr
.getCheckSquares(lastMove
);
881 this.vr
.play(lastMove
, "ingame");
883 delete localStorage
["newgame"];
884 this.setStorage(); //in case of interruptions
886 else if (mode
== "computer")
888 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
889 if (this.mycolor
== 'b')
890 setTimeout(this.playComputerMove
, 500);
892 //else: against a (IRL) friend: nothing more to do
894 playComputerMove: function() {
895 const timeStart
= Date
.now();
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
946 // (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 coords
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 // Next condition: classList.contains(piece) fails because of marks
976 while (landing
.tagName
== "IMG")
977 landing
= landing
.parentNode
;
978 if (this.start
.id
== landing
.id
)
980 // A click: selectedPiece and possibleMoves are already filled
983 // OK: process move attempt
984 let endSquare
= this.getSquareFromId(landing
.id
);
985 let moves
= this.findMatchingMoves(endSquare
);
986 this.possibleMoves
= [];
987 if (moves
.length
> 1)
988 this.choices
= moves
;
989 else if (moves
.length
==1)
991 // Else: impossible move
992 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
993 delete this.selectedPiece
;
994 this.selectedPiece
= null;
996 findMatchingMoves: function(endSquare
) {
997 // Run through moves list and return the matching set (if promotions...)
999 this.possibleMoves
.forEach(function(m
) {
1000 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1005 animateMove: function(move) {
1006 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1007 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1008 let rectStart
= startSquare
.getBoundingClientRect();
1009 let rectEnd
= endSquare
.getBoundingClientRect();
1010 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1012 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1013 // HACK for animation (with positive translate, image slides "under background")
1014 // Possible improvement: just alter squares on the piece's way...
1015 squares
= document
.getElementsByClassName("board");
1016 for (let i
=0; i
<squares
.length
; i
++)
1018 let square
= squares
.item(i
);
1019 if (square
.id
!= this.getSquareId(move.start
))
1020 square
.style
.zIndex
= "-1";
1022 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1023 translation
.y
+ "px)";
1024 movingPiece
.style
.transitionDuration
= "0.2s";
1025 movingPiece
.style
.zIndex
= "3000";
1027 for (let i
=0; i
<squares
.length
; i
++)
1028 squares
.item(i
).style
.zIndex
= "auto";
1029 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1033 play: function(move, programmatic
) {
1036 // Navigate after game is over
1037 if (this.cursor
>= this.vr
.moves
.length
)
1038 return; //already at the end
1039 move = this.vr
.moves
[this.cursor
++];
1041 if (!!programmatic
) //computer or human opponent
1043 this.animateMove(move);
1046 // Not programmatic, or animation is over
1047 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1048 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1049 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
1050 if (this.mode
!= "idle")
1052 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1053 this.vr
.play(move, "ingame");
1057 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1058 this.$forceUpdate(); //TODO: ?!
1060 if (this.mode
== "human")
1061 this.updateStorage(); //after our moves and opponent moves
1062 if (this.mode
!= "idle")
1064 const eog
= this.vr
.checkGameOver();
1068 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1069 setTimeout(this.playComputerMove
, 500);
1072 // Navigate after game is over
1073 if (this.cursor
== 0)
1074 return; //already at the beginning
1075 if (this.cursor
== this.vr
.moves
.length
)
1076 this.incheck
= []; //in case of...
1077 const move = this.vr
.moves
[--this.cursor
];
1078 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1079 this.$forceUpdate(); //TODO: ?!
1081 undoInGame: function() {
1082 const lm
= this.vr
.lastMove
;