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 hints: (getCookie("hints") === "1" ? true : false),
21 //color: TODO (lichess, chess.com, chesstempo)
22 //sound: TODO (0,1, 2)
26 const [sizeX
,sizeY
] = VariantRules
.size
;
27 const smallScreen
= (screen
.width
<= 420);
28 // Precompute hints squares to facilitate rendering
29 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
30 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
31 // Also precompute in-check squares
32 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
33 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
34 let elementArray
= [];
39 on: { click: this.clickGameSeek
},
40 attrs: { "aria-label": 'New online game' },
43 "bottom": true, //display below
45 "playing": this.mode
== "human",
49 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
51 if (["idle","computer"].includes(this.mode
))
56 on: { click: this.clickComputerGame
},
57 attrs: { "aria-label": 'New game VS computer' },
61 "playing": this.mode
== "computer",
65 [h('i', { 'class': { "material-icons": true } }, "computer")])
68 if (["idle","friend"].includes(this.mode
))
73 on: { click: this.clickFriendGame
},
74 attrs: { "aria-label": 'New IRL game' },
78 "playing": this.mode
== "friend",
82 [h('i', { 'class': { "material-icons": true } }, "people")])
87 const square00
= document
.getElementById("sq-0-0");
88 const squareWidth
= !!square00
89 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
91 const settingsBtnElt
= document
.getElementById("settingsBtn");
92 const indicWidth
= !!settingsBtnElt
//-2 for border:
93 ? parseFloat(window
.getComputedStyle(settingsBtnElt
).height
.slice(0,-2)) - 2
95 if (this.mode
== "human")
97 let connectedIndic
= h(
101 "topindicator": true,
103 "connected": this.oppConnected
,
104 "disconnected": !this.oppConnected
,
107 "width": indicWidth
+ "px",
108 "height": indicWidth
+ "px",
112 elementArray
.push(connectedIndic
);
118 "topindicator": true,
120 "white-turn": this.vr
.turn
=="w",
121 "black-turn": this.vr
.turn
=="b",
124 "width": indicWidth
+ "px",
125 "height": indicWidth
+ "px",
129 elementArray
.push(turnIndic
);
133 on: { click: this.showSettings
},
135 "aria-label": 'Settings',
140 "topindicator": true,
142 "settings-btn": true,
143 "small": smallScreen
,
146 [h('i', { 'class': { "material-icons": true } }, "settings")]
148 elementArray
.push(settingsBtn
);
149 let choices
= h('div',
151 attrs: { "id": "choices" },
152 'class': { 'row': true },
154 "display": this.choices
.length
>0?"block":"none",
155 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
156 "width": (this.choices
.length
* squareWidth
) + "px",
157 "height": squareWidth
+ "px",
160 this.choices
.map( m
=> { //a "choice" is a move
165 ['board'+sizeY
]: true,
168 'width': (100/this.choices
.length
) + "%",
169 'padding-bottom': (100/this.choices
.length
) + "%",
174 attrs: { "src": '/images/pieces/' +
175 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
176 'class': { 'choice-piece': true },
177 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
183 // Create board element (+ reserves if needed by variant or mode)
184 let gameDiv
= h('div',
186 'class': { 'game': true },
188 [_
.range(sizeX
).map(i
=> {
189 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
196 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
198 _
.range(sizeY
).map(j
=> {
199 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
201 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
209 'ghost': !!this.selectedPiece
210 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
213 src: "/images/pieces/" +
214 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
220 if (this.hints
&& hintSquares
[ci
][cj
])
230 src: "/images/mark.svg",
236 const lm
= this.vr
.lastMove
;
237 const showLight
= this.hints
&&
238 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
244 ['board'+sizeY
]: true,
245 'light-square': (i
+j
)%2==0,
246 'dark-square': (i
+j
)%2==1,
247 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
248 'incheck': showLight
&& incheckSq
[ci
][cj
],
251 id: this.getSquareId({x:ci
,y:cj
}),
260 if (this.mode
!= "idle")
265 on: { click: this.resign
},
266 attrs: { "aria-label": 'Resign' },
270 "small": smallScreen
,
273 [h('i', { 'class': { "material-icons": true } }, "flag")])
276 else if (this.vr
.moves
.length
> 0)
278 // A game finished, and another is not started yet: allow navigation
279 actionArray
= actionArray
.concat([
282 on: { click: e
=> this.undo() },
283 attrs: { "aria-label": 'Undo' },
285 "small": smallScreen
,
289 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
292 on: { click: e
=> this.play() },
293 attrs: { "aria-label": 'Play' },
294 "class": { "small": smallScreen
},
296 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
300 if (this.mode
== "friend")
302 actionArray
= actionArray
.concat(
306 on: { click: this.undoInGame
},
307 attrs: { "aria-label": 'Undo' },
309 "small": smallScreen
,
313 [h('i', { 'class': { "material-icons": true } }, "undo")]
317 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
318 attrs: { "aria-label": 'Flip' },
319 "class": { "small": smallScreen
},
321 [h('i', { 'class': { "material-icons": true } }, "cached")]
325 elementArray
.push(gameDiv
);
326 if (!!this.vr
.reserve
)
328 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
329 let myReservePiecesArray
= [];
330 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
332 myReservePiecesArray
.push(h('div',
334 'class': {'board':true, ['board'+sizeY
]:true},
335 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
340 'class': {"piece":true},
342 "src": "/images/pieces/" +
343 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
347 {"class": { "reserve-count": true } },
348 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
352 let oppReservePiecesArray
= [];
353 const oppCol
= this.vr
.getOppCol(this.mycolor
);
354 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
356 oppReservePiecesArray
.push(h('div',
358 'class': {'board':true, ['board'+sizeY
]:true},
359 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
364 'class': {"piece":true},
366 "src": "/images/pieces/" +
367 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
371 {"class": { "reserve-count": true } },
372 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
376 let reserves
= h('div',
388 "reserve-row-1": true,
394 { 'class': { 'row': true }},
395 oppReservePiecesArray
399 elementArray
.push(reserves
);
401 const eogMessage
= this.getEndgameMessage(this.score
);
405 attrs: { "id": "modal-eog", type: "checkbox" },
406 "class": { "modal": true },
410 attrs: { "role": "dialog", "aria-labelledby": "modal-eog" },
415 "class": { "card": true, "smallpad": true },
420 attrs: { "for": "modal-eog" },
421 "class": { "modal-close": true },
426 "class": { "section": true },
427 domProps: { innerHTML: eogMessage
},
435 elementArray
= elementArray
.concat(modalEog
);
437 const modalNewgame
= [
440 attrs: { "id": "modal-newgame", type: "checkbox" },
441 "class": { "modal": true },
445 attrs: { "role": "dialog", "aria-labelledby": "modal-newgame" },
450 "class": { "card": true, "smallpad": true },
455 attrs: { "id": "close-newgame", "for": "modal-newgame" },
456 "class": { "modal-close": true },
461 "class": { "section": true },
462 domProps: { innerHTML: "New game" },
467 "class": { "section": true },
468 domProps: { innerHTML: "Waiting for opponent..." },
476 elementArray
= elementArray
.concat(modalNewgame
);
477 const modalFenEdit
= [
480 attrs: { "id": "modal-fenedit", type: "checkbox" },
481 "class": { "modal": true },
485 attrs: { "role": "dialog", "aria-labelledby": "modal-fenedit" },
490 "class": { "card": true, "smallpad": true },
495 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
496 "class": { "modal-close": true },
501 "class": { "section": true },
502 domProps: { innerHTML: "Position + flags (FEN):" },
510 value: VariantRules
.GenRandInitFen(),
518 const fen
= document
.getElementById("input-fen").value
;
519 document
.getElementById("modal-fenedit").checked
= false;
520 this.newGame("friend", fen
);
523 domProps: { innerHTML: "Ok" },
530 document
.getElementById("input-fen").value
=
531 VariantRules
.GenRandInitFen();
534 domProps: { innerHTML: "Random" },
542 elementArray
= elementArray
.concat(modalFenEdit
);
543 const modalSettings
= [
546 attrs: { "id": "modal-settings", type: "checkbox" },
547 "class": { "modal": true },
551 attrs: { "role": "dialog", "aria-labelledby": "modal-settings" },
556 "class": { "card": true, "smallpad": true },
561 attrs: { "id": "close-settings", "for": "modal-settings" },
562 "class": { "modal-close": true },
567 "class": { "section": true },
568 domProps: { innerHTML: "User settings" },
571 // https://minicss.org/docs#forms-and-input
572 h('p', { domProps: { innerHTML: "TODO: hints" } }),
573 h('p', { domProps: { innerHTML: "TODO: board(color)" } }),
574 h('p', { domProps: { innerHTML: "TODO: sound(level)" } }),
580 elementArray
= elementArray
.concat(modalSettings
);
581 const actions
= h('div',
583 attrs: { "id": "actions" },
584 'class': { 'text-center': true },
588 elementArray
.push(actions
);
589 if (this.score
!= "*")
593 { attrs: { id: "pgn-div" } },
605 attrs: { id: "pgn-game" },
606 on: { click: this.download
},
607 domProps: { innerHTML: this.pgnTxt
}
614 else if (this.mode
!= "idle")
619 { attrs: { id: "fen-div" } },
623 attrs: { id: "fen-string" },
624 domProps: { innerHTML: this.vr
.getFen() }
637 "col-md-offset-2":true,
639 "col-lg-offset-3":true,
641 // NOTE: click = mousedown + mouseup
643 mousedown: this.mousedown
,
644 mousemove: this.mousemove
,
645 mouseup: this.mouseup
,
646 touchstart: this.mousedown
,
647 touchmove: this.mousemove
,
648 touchend: this.mouseup
,
654 created: function() {
655 const url
= socketUrl
;
656 const continuation
= (localStorage
.getItem("variant") === variant
);
657 this.myid
= continuation
? localStorage
.getItem("myid") : getRandString();
660 // HACK: play a small silent sound to allow "new game" sound later
661 // if tab not focused (TODO: does it really work ?!)
662 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
664 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
665 const socketOpenListener
= () => {
668 const fen
= localStorage
.getItem("fen");
669 const mycolor
= localStorage
.getItem("mycolor");
670 const oppid
= localStorage
.getItem("oppid");
671 const moves
= JSON
.parse(localStorage
.getItem("moves"));
672 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
673 // Send ping to server (answer pong if opponent is connected)
674 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
676 else if (localStorage
.getItem("newgame") === variant
)
678 // New game request has been cancelled on disconnect
679 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
682 const socketMessageListener
= msg
=> {
683 const data
= JSON
.parse(msg
.data
);
686 case "newgame": //opponent found
687 // oppid: opponent socket ID
688 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
690 case "newmove": //..he played!
691 this.play(data
.move, "animate");
693 case "pong": //received if we sent a ping (game still alive on our side)
694 this.oppConnected
= true;
695 const L
= this.vr
.moves
.length
;
696 // Send our "last state" informations to opponent
697 this.conn
.send(JSON
.stringify({
700 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
704 case "lastate": //got opponent infos about last move (we might have resigned)
705 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
708 this.conn
.send(JSON
.stringify({
715 else if (data
.movesCount
< 0)
718 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
720 else if (data
.movesCount
< this.vr
.moves
.length
)
722 // We must tell last move to opponent
723 const L
= this.vr
.moves
.length
;
724 this.conn
.send(JSON
.stringify({
727 lastMove:this.vr
.moves
[L
-1],
731 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
732 this.play(data
.lastMove
, "animate");
734 case "resign": //..you won!
735 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
737 // TODO: also use (dis)connect info to count online players?
740 if (this.mode
== "human" && this.oppid
== data
.id
)
741 this.oppConnected
= (data
.code
== "connect");
745 const socketCloseListener
= () => {
746 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
747 this.conn
.addEventListener('open', socketOpenListener
);
748 this.conn
.addEventListener('message', socketMessageListener
);
749 this.conn
.addEventListener('close', socketCloseListener
);
751 this.conn
.onopen
= socketOpenListener
;
752 this.conn
.onmessage
= socketMessageListener
;
753 this.conn
.onclose
= socketCloseListener
;
754 // Listen to keyboard left/right to navigate in game
755 document
.onkeydown
= event
=> {
756 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
757 && [37,39].includes(event
.keyCode
))
759 event
.preventDefault();
760 if (event
.keyCode
== 37) //Back
768 download: function() {
769 let content
= document
.getElementById("pgn-game").innerHTML
;
770 content
= content
.replace(/<br>/g, "\n");
771 // Prepare and trigger download link
772 let downloadAnchor
= document
.getElementById("download");
773 downloadAnchor
.setAttribute("download", "game.pgn");
774 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
775 encodeURIComponent(content
);
776 downloadAnchor
.click();
778 endGame: function(score
) {
780 let modalBox
= document
.getElementById("modal-eog");
781 modalBox
.checked
= true;
782 // Variants may have special PGN structure (so next function isn't defined here)
783 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
784 setTimeout(() => { modalBox
.checked
= false; }, 2000);
785 if (this.mode
== "human")
788 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
791 getEndgameMessage: function(score
) {
792 let eogMessage
= "Unfinished";
796 eogMessage
= "White win";
799 eogMessage
= "Black win";
807 setStorage: function() {
808 localStorage
.setItem("myid", this.myid
);
809 localStorage
.setItem("variant", variant
);
810 localStorage
.setItem("mycolor", this.mycolor
);
811 localStorage
.setItem("oppid", this.oppid
);
812 localStorage
.setItem("fenStart", this.fenStart
);
813 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
814 localStorage
.setItem("fen", this.vr
.getFen());
816 updateStorage: function() {
817 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
818 localStorage
.setItem("fen", this.vr
.getFen());
820 clearStorage: function() {
821 delete localStorage
["variant"];
822 delete localStorage
["myid"];
823 delete localStorage
["mycolor"];
824 delete localStorage
["oppid"];
825 delete localStorage
["fenStart"];
826 delete localStorage
["fen"];
827 delete localStorage
["moves"];
829 // HACK because mini-css tooltips are persistent after click...
830 getRidOfTooltip: function(elt
) {
831 elt
.style
.visibility
= "hidden";
832 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
834 showSettings: function(e
) {
835 this.getRidOfTooltip(e
.currentTarget
);
836 document
.getElementById("modal-settings").checked
= true;
838 toggleHints: function() {
839 this.hints
= !this.hints
;
840 setCookie("hints", this.hints
? "1" : "0");
842 clickGameSeek: function(e
) {
843 this.getRidOfTooltip(e
.currentTarget
);
844 if (this.mode
== "human")
845 return; //no newgame while playing
848 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
849 delete localStorage
["newgame"]; //cancel game seek
853 this.newGame("human");
855 clickComputerGame: function(e
) {
856 this.getRidOfTooltip(e
.currentTarget
);
857 if (this.mode
== "human")
858 return; //no newgame while playing
859 this.newGame("computer");
861 clickFriendGame: function(e
) {
862 this.getRidOfTooltip(e
.currentTarget
);
863 document
.getElementById("modal-fenedit").checked
= true;
865 resign: function(e
) {
866 this.getRidOfTooltip(e
.currentTarget
);
867 if (this.mode
== "human" && this.oppConnected
)
870 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
871 } catch (INVALID_STATE_ERR
) {
872 return; //socket is not ready (and not yet reconnected)
875 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
877 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
878 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
879 console
.log(fen
); //DEBUG
880 if (mode
=="human" && !oppId
)
882 const storageVariant
= localStorage
.getItem("variant");
883 if (!!storageVariant
&& storageVariant
!== variant
)
885 alert("Finish your " + storageVariant
+ " game first!");
888 // Send game request and wait..
889 localStorage
["newgame"] = variant
;
891 this.clearStorage(); //in case of
893 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
894 } catch (INVALID_STATE_ERR
) {
895 return; //nothing achieved
897 if (continuation
!== "reconnect") //TODO: bad HACK...
899 let modalBox
= document
.getElementById("modal-newgame");
900 modalBox
.checked
= true;
901 setTimeout(() => { modalBox
.checked
= false; }, 2000);
905 this.vr
= new VariantRules(fen
, moves
|| []);
907 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
909 this.incheck
= []; //in case of
910 this.fenStart
= (continuation
? localStorage
.getItem("fenStart") : fen
);
916 // Not playing sound on game continuation:
917 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
918 document
.getElementById("modal-newgame").checked
= false;
921 this.oppConnected
= true;
922 this.mycolor
= color
;
924 if (!!moves
&& moves
.length
> 0) //imply continuation
926 const lastMove
= moves
[moves
.length
-1];
927 this.vr
.undo(lastMove
);
928 this.incheck
= this.vr
.getCheckSquares(lastMove
);
929 this.vr
.play(lastMove
, "ingame");
931 delete localStorage
["newgame"];
932 this.setStorage(); //in case of interruptions
934 else if (mode
== "computer")
936 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
937 if (this.mycolor
== 'b')
938 setTimeout(this.playComputerMove
, 500);
940 //else: against a (IRL) friend: nothing more to do
942 playComputerMove: function() {
943 const timeStart
= Date
.now();
944 const compMove
= this.vr
.getComputerMove();
945 // (first move) HACK: avoid selecting elements before they appear on page:
946 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
947 setTimeout(() => this.play(compMove
, "animate"), delay
);
949 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
950 getSquareId: function(o
) {
951 // NOTE: a separator is required to allow any size of board
952 return "sq-" + o
.x
+ "-" + o
.y
;
955 getSquareFromId: function(id
) {
956 let idParts
= id
.split('-');
957 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
959 mousedown: function(e
) {
960 e
= e
|| window
.event
;
963 while (!ingame
&& elem
!== null)
965 if (elem
.classList
.contains("game"))
970 elem
= elem
.parentElement
;
972 if (!ingame
) //let default behavior (click on button...)
974 e
.preventDefault(); //disable native drag & drop
975 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
977 // Next few lines to center the piece on mouse cursor
978 let rect
= e
.target
.parentNode
.getBoundingClientRect();
980 x: rect
.x
+ rect
.width
/2,
981 y: rect
.y
+ rect
.width
/2,
982 id: e
.target
.parentNode
.id
984 this.selectedPiece
= e
.target
.cloneNode();
985 this.selectedPiece
.style
.position
= "absolute";
986 this.selectedPiece
.style
.top
= 0;
987 this.selectedPiece
.style
.display
= "inline-block";
988 this.selectedPiece
.style
.zIndex
= 3000;
989 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
990 const iCanPlay
= this.mode
!="idle"
991 && (this.mode
=="friend" || this.vr
.canIplay(this.mycolor
,startSquare
));
992 this.possibleMoves
= iCanPlay
? this.vr
.getPossibleMovesFrom(startSquare
) : [];
993 // Next line add moving piece just after current image
994 // (required for Crazyhouse reserve)
995 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
998 mousemove: function(e
) {
999 if (!this.selectedPiece
)
1001 e
= e
|| window
.event
;
1002 // If there is an active element, move it around
1003 if (!!this.selectedPiece
)
1005 const [offsetX
,offsetY
] = !!e
.clientX
1006 ? [e
.clientX
,e
.clientY
] //desktop browser
1007 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1008 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1009 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1012 mouseup: function(e
) {
1013 if (!this.selectedPiece
)
1015 e
= e
|| window
.event
;
1016 // Read drop target (or parentElement, parentNode... if type == "img")
1017 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1018 const [offsetX
,offsetY
] = !!e
.clientX
1019 ? [e
.clientX
,e
.clientY
]
1020 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1021 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1022 this.selectedPiece
.style
.zIndex
= 3000;
1023 // Next condition: classList.contains(piece) fails because of marks
1024 while (landing
.tagName
== "IMG")
1025 landing
= landing
.parentNode
;
1026 if (this.start
.id
== landing
.id
)
1028 // A click: selectedPiece and possibleMoves are already filled
1031 // OK: process move attempt
1032 let endSquare
= this.getSquareFromId(landing
.id
);
1033 let moves
= this.findMatchingMoves(endSquare
);
1034 this.possibleMoves
= [];
1035 if (moves
.length
> 1)
1036 this.choices
= moves
;
1037 else if (moves
.length
==1)
1038 this.play(moves
[0]);
1039 // Else: impossible move
1040 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1041 delete this.selectedPiece
;
1042 this.selectedPiece
= null;
1044 findMatchingMoves: function(endSquare
) {
1045 // Run through moves list and return the matching set (if promotions...)
1047 this.possibleMoves
.forEach(function(m
) {
1048 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1053 animateMove: function(move) {
1054 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1055 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1056 let rectStart
= startSquare
.getBoundingClientRect();
1057 let rectEnd
= endSquare
.getBoundingClientRect();
1058 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1060 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1061 // HACK for animation (with positive translate, image slides "under background")
1062 // Possible improvement: just alter squares on the piece's way...
1063 squares
= document
.getElementsByClassName("board");
1064 for (let i
=0; i
<squares
.length
; i
++)
1066 let square
= squares
.item(i
);
1067 if (square
.id
!= this.getSquareId(move.start
))
1068 square
.style
.zIndex
= "-1";
1070 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1071 translation
.y
+ "px)";
1072 movingPiece
.style
.transitionDuration
= "0.2s";
1073 movingPiece
.style
.zIndex
= "3000";
1075 for (let i
=0; i
<squares
.length
; i
++)
1076 squares
.item(i
).style
.zIndex
= "auto";
1077 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1081 play: function(move, programmatic
) {
1084 // Navigate after game is over
1085 if (this.cursor
>= this.vr
.moves
.length
)
1086 return; //already at the end
1087 move = this.vr
.moves
[this.cursor
++];
1089 if (!!programmatic
) //computer or human opponent
1091 this.animateMove(move);
1094 // Not programmatic, or animation is over
1095 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1096 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1097 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
1098 if (this.mode
!= "idle")
1100 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1101 this.vr
.play(move, "ingame");
1105 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1106 this.$forceUpdate(); //TODO: ?!
1108 if (this.mode
== "human")
1109 this.updateStorage(); //after our moves and opponent moves
1110 if (this.mode
!= "idle")
1112 const eog
= this.vr
.checkGameOver();
1116 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1117 setTimeout(this.playComputerMove
, 500);
1120 // Navigate after game is over
1121 if (this.cursor
== 0)
1122 return; //already at the beginning
1123 if (this.cursor
== this.vr
.moves
.length
)
1124 this.incheck
= []; //in case of...
1125 const move = this.vr
.moves
[--this.cursor
];
1126 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1127 this.$forceUpdate(); //TODO: ?!
1129 undoInGame: function() {
1130 const lm
= this.vr
.lastMove
;