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: getCookie("color", "lichess"), //lichess, chesscom or chesstempo
22 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
23 sound: parseInt(getCookie("sound", "2")),
27 const [sizeX
,sizeY
] = VariantRules
.size
;
28 console
.log(sizeX
+ " " + sizeY
);
29 const smallScreen
= (screen
.width
<= 420);
30 // Precompute hints squares to facilitate rendering
31 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
32 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
33 // Also precompute in-check squares
34 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
35 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
36 let elementArray
= [];
41 on: { click: this.clickGameSeek
},
42 attrs: { "aria-label": 'New online game' },
45 "bottom": true, //display below
47 "playing": this.mode
== "human",
51 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
53 if (["idle","computer"].includes(this.mode
))
58 on: { click: this.clickComputerGame
},
59 attrs: { "aria-label": 'New game VS computer' },
63 "playing": this.mode
== "computer",
67 [h('i', { 'class': { "material-icons": true } }, "computer")])
70 if (["idle","friend"].includes(this.mode
))
75 on: { click: this.clickFriendGame
},
76 attrs: { "aria-label": 'New IRL game' },
80 "playing": this.mode
== "friend",
84 [h('i', { 'class': { "material-icons": true } }, "people")])
89 const square00
= document
.getElementById("sq-0-0");
90 const squareWidth
= !!square00
91 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
93 const settingsBtnElt
= document
.getElementById("settingsBtn");
94 const indicWidth
= !!settingsBtnElt
//-2 for border:
95 ? parseFloat(window
.getComputedStyle(settingsBtnElt
).height
.slice(0,-2)) - 2
96 : (smallScreen
? 31 : 37);
97 if (this.mode
== "human")
99 let connectedIndic
= h(
103 "topindicator": true,
105 "connected": this.oppConnected
,
106 "disconnected": !this.oppConnected
,
109 "width": indicWidth
+ "px",
110 "height": indicWidth
+ "px",
114 elementArray
.push(connectedIndic
);
120 "topindicator": true,
122 "white-turn": this.vr
.turn
=="w",
123 "black-turn": this.vr
.turn
=="b",
126 "width": indicWidth
+ "px",
127 "height": indicWidth
+ "px",
131 elementArray
.push(turnIndic
);
135 on: { click: this.showSettings
},
137 "aria-label": 'Settings',
142 "topindicator": true,
144 "settings-btn": !smallScreen
,
145 "settings-btn-small": smallScreen
,
148 [h('i', { 'class': { "material-icons": true } }, "settings")]
150 elementArray
.push(settingsBtn
);
151 let choices
= h('div',
153 attrs: { "id": "choices" },
154 'class': { 'row': true },
156 "display": this.choices
.length
>0?"block":"none",
157 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
158 "width": (this.choices
.length
* squareWidth
) + "px",
159 "height": squareWidth
+ "px",
162 this.choices
.map( m
=> { //a "choice" is a move
167 ['board'+sizeY
]: true,
170 'width': (100/this.choices
.length
) + "%",
171 'padding-bottom': (100/this.choices
.length
) + "%",
176 attrs: { "src": '/images/pieces/' +
177 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
178 'class': { 'choice-piece': true },
179 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
185 // Create board element (+ reserves if needed by variant or mode)
186 const lm
= this.vr
.lastMove
;
187 const showLight
= this.hints
&&
188 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
189 let gameDiv
= h('div',
191 'class': { 'game': true },
193 [_
.range(sizeX
).map(i
=> {
194 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
201 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
203 _
.range(sizeY
).map(j
=> {
204 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
206 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
214 'ghost': !!this.selectedPiece
215 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
218 src: "/images/pieces/" +
219 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
225 if (this.hints
&& hintSquares
[ci
][cj
])
235 src: "/images/mark.svg",
246 ['board'+sizeY
]: true,
247 'light-square': (i
+j
)%2==0,
248 'dark-square': (i
+j
)%2==1,
250 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
251 'incheck': showLight
&& incheckSq
[ci
][cj
],
254 id: this.getSquareId({x:ci
,y:cj
}),
263 if (this.mode
!= "idle")
268 on: { click: this.resign
},
269 attrs: { "aria-label": 'Resign' },
273 "small": smallScreen
,
276 [h('i', { 'class': { "material-icons": true } }, "flag")])
279 else if (this.vr
.moves
.length
> 0)
281 // A game finished, and another is not started yet: allow navigation
282 actionArray
= actionArray
.concat([
285 on: { click: e
=> this.undo() },
286 attrs: { "aria-label": 'Undo' },
288 "small": smallScreen
,
292 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
295 on: { click: e
=> this.play() },
296 attrs: { "aria-label": 'Play' },
297 "class": { "small": smallScreen
},
299 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
303 if (this.mode
== "friend")
305 actionArray
= actionArray
.concat(
309 on: { click: this.undoInGame
},
310 attrs: { "aria-label": 'Undo' },
312 "small": smallScreen
,
316 [h('i', { 'class': { "material-icons": true } }, "undo")]
320 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
321 attrs: { "aria-label": 'Flip' },
322 "class": { "small": smallScreen
},
324 [h('i', { 'class': { "material-icons": true } }, "cached")]
328 elementArray
.push(gameDiv
);
329 if (!!this.vr
.reserve
)
331 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
332 let myReservePiecesArray
= [];
333 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
335 myReservePiecesArray
.push(h('div',
337 'class': {'board':true, ['board'+sizeY
]:true},
338 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
343 'class': {"piece":true},
345 "src": "/images/pieces/" +
346 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
350 {"class": { "reserve-count": true } },
351 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
355 let oppReservePiecesArray
= [];
356 const oppCol
= this.vr
.getOppCol(this.mycolor
);
357 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
359 oppReservePiecesArray
.push(h('div',
361 'class': {'board':true, ['board'+sizeY
]:true},
362 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
367 'class': {"piece":true},
369 "src": "/images/pieces/" +
370 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
374 {"class": { "reserve-count": true } },
375 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
379 let reserves
= h('div',
391 "reserve-row-1": true,
397 { 'class': { 'row': true }},
398 oppReservePiecesArray
402 elementArray
.push(reserves
);
404 const eogMessage
= this.getEndgameMessage(this.score
);
408 attrs: { "id": "modal-eog", type: "checkbox" },
409 "class": { "modal": true },
413 attrs: { "role": "dialog", "aria-labelledby": "modal-eog" },
418 "class": { "card": true, "smallpad": true },
423 attrs: { "for": "modal-eog" },
424 "class": { "modal-close": true },
429 "class": { "section": true },
430 domProps: { innerHTML: eogMessage
},
438 elementArray
= elementArray
.concat(modalEog
);
440 // NOTE: this modal could be in Pug view (no usage of Vue functions or variables)
441 const modalNewgame
= [
444 attrs: { "id": "modal-newgame", type: "checkbox" },
445 "class": { "modal": true },
449 attrs: { "role": "dialog", "aria-labelledby": "modal-newgame" },
454 "class": { "card": true, "smallpad": true },
459 attrs: { "id": "close-newgame", "for": "modal-newgame" },
460 "class": { "modal-close": true },
465 "class": { "section": true },
466 domProps: { innerHTML: "New game" },
471 "class": { "section": true },
472 domProps: { innerHTML: "Waiting for opponent..." },
480 elementArray
= elementArray
.concat(modalNewgame
);
481 const modalFenEdit
= [
484 attrs: { "id": "modal-fenedit", type: "checkbox" },
485 "class": { "modal": true },
489 attrs: { "role": "dialog", "aria-labelledby": "modal-fenedit" },
494 "class": { "card": true, "smallpad": true },
499 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
500 "class": { "modal-close": true },
505 "class": { "section": true },
506 domProps: { innerHTML: "Position + flags (FEN):" },
514 value: VariantRules
.GenRandInitFen(),
522 const fen
= document
.getElementById("input-fen").value
;
523 document
.getElementById("modal-fenedit").checked
= false;
524 this.newGame("friend", fen
);
527 domProps: { innerHTML: "Ok" },
534 document
.getElementById("input-fen").value
=
535 VariantRules
.GenRandInitFen();
538 domProps: { innerHTML: "Random" },
546 elementArray
= elementArray
.concat(modalFenEdit
);
547 const modalSettings
= [
550 attrs: { "id": "modal-settings", type: "checkbox" },
551 "class": { "modal": true },
555 attrs: { "role": "dialog", "aria-labelledby": "modal-settings" },
560 "class": { "card": true, "smallpad": true },
565 attrs: { "id": "close-settings", "for": "modal-settings" },
566 "class": { "modal-close": true },
571 "class": { "section": true },
572 domProps: { innerHTML: "Preferences" },
578 //h('legend', { domProps: { innerHTML: "Legend title" } }),
581 attrs: { for: "setHints" },
582 domProps: { innerHTML: "Show hints?" },
592 on: { "change": this.toggleHints
},
602 attrs: { for: "selectColor" },
603 domProps: { innerHTML: "Board colors" },
608 attrs: { "id": "selectColor" },
609 on: { "change": this.setColor
},
618 attrs: { "selected": this.color
=="lichess" },
627 attrs: { "selected": this.color
=="chesscom" },
633 "value": "chesstempo",
636 attrs: { "selected": this.color
=="chesstempo" },
648 attrs: { for: "selectSound" },
649 domProps: { innerHTML: "Play sounds?" },
654 attrs: { "id": "selectSound" },
655 on: { "change": this.setSound
},
664 attrs: { "selected": this.sound
==0 },
673 attrs: { "selected": this.sound
==1 },
682 attrs: { "selected": this.sound
==2 },
694 elementArray
= elementArray
.concat(modalSettings
);
695 const actions
= h('div',
697 attrs: { "id": "actions" },
698 'class': { 'text-center': true },
702 elementArray
.push(actions
);
703 if (this.score
!= "*")
708 attrs: { id: "pgn-div" },
709 "class": { "section-content": true },
722 attrs: { id: "pgn-game" },
723 domProps: { innerHTML: this.pgnTxt
}
728 attrs: { "id": "downloadBtn" },
729 on: { click: this.download
},
730 domProps: { innerHTML: "Download game" },
737 else if (this.mode
!= "idle")
743 attrs: { id: "fen-div" },
744 "class": { "section-content": true },
749 attrs: { id: "fen-string" },
750 domProps: { innerHTML: this.vr
.getFen() }
763 "col-md-offset-2":true,
765 "col-lg-offset-3":true,
767 // NOTE: click = mousedown + mouseup
769 mousedown: this.mousedown
,
770 mousemove: this.mousemove
,
771 mouseup: this.mouseup
,
772 touchstart: this.mousedown
,
773 touchmove: this.mousemove
,
774 touchend: this.mouseup
,
780 created: function() {
781 const url
= socketUrl
;
782 const continuation
= (localStorage
.getItem("variant") === variant
);
783 this.myid
= continuation
? localStorage
.getItem("myid") : getRandString();
786 // HACK: play a small silent sound to allow "new game" sound later
787 // if tab not focused (TODO: does it really work ?!)
788 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
790 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
791 const socketOpenListener
= () => {
794 const fen
= localStorage
.getItem("fen");
795 const mycolor
= localStorage
.getItem("mycolor");
796 const oppid
= localStorage
.getItem("oppid");
797 const moves
= JSON
.parse(localStorage
.getItem("moves"));
798 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
799 // Send ping to server (answer pong if opponent is connected)
800 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
802 else if (localStorage
.getItem("newgame") === variant
)
804 // New game request has been cancelled on disconnect
805 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
808 const socketMessageListener
= msg
=> {
809 const data
= JSON
.parse(msg
.data
);
812 case "newgame": //opponent found
813 // oppid: opponent socket ID
814 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
816 case "newmove": //..he played!
817 this.play(data
.move, "animate");
819 case "pong": //received if we sent a ping (game still alive on our side)
820 this.oppConnected
= true;
821 const L
= this.vr
.moves
.length
;
822 // Send our "last state" informations to opponent
823 this.conn
.send(JSON
.stringify({
826 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
830 case "lastate": //got opponent infos about last move (we might have resigned)
831 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
834 this.conn
.send(JSON
.stringify({
841 else if (data
.movesCount
< 0)
844 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
846 else if (data
.movesCount
< this.vr
.moves
.length
)
848 // We must tell last move to opponent
849 const L
= this.vr
.moves
.length
;
850 this.conn
.send(JSON
.stringify({
853 lastMove:this.vr
.moves
[L
-1],
857 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
858 this.play(data
.lastMove
, "animate");
860 case "resign": //..you won!
861 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
863 // TODO: also use (dis)connect info to count online players?
866 if (this.mode
== "human" && this.oppid
== data
.id
)
867 this.oppConnected
= (data
.code
== "connect");
871 const socketCloseListener
= () => {
872 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
873 this.conn
.addEventListener('open', socketOpenListener
);
874 this.conn
.addEventListener('message', socketMessageListener
);
875 this.conn
.addEventListener('close', socketCloseListener
);
877 this.conn
.onopen
= socketOpenListener
;
878 this.conn
.onmessage
= socketMessageListener
;
879 this.conn
.onclose
= socketCloseListener
;
880 // Listen to keyboard left/right to navigate in game
881 document
.onkeydown
= event
=> {
882 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
883 && [37,39].includes(event
.keyCode
))
885 event
.preventDefault();
886 if (event
.keyCode
== 37) //Back
894 download: function() {
895 let content
= document
.getElementById("pgn-game").innerHTML
;
896 content
= content
.replace(/<br>/g, "\n");
897 // Prepare and trigger download link
898 let downloadAnchor
= document
.getElementById("download");
899 downloadAnchor
.setAttribute("download", "game.pgn");
900 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
901 encodeURIComponent(content
);
902 downloadAnchor
.click();
904 endGame: function(score
) {
906 let modalBox
= document
.getElementById("modal-eog");
907 modalBox
.checked
= true;
908 // Variants may have special PGN structure (so next function isn't defined here)
909 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
910 setTimeout(() => { modalBox
.checked
= false; }, 2000);
911 if (this.mode
== "human")
914 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
917 getEndgameMessage: function(score
) {
918 let eogMessage
= "Unfinished";
922 eogMessage
= "White win";
925 eogMessage
= "Black win";
933 setStorage: function() {
934 localStorage
.setItem("myid", this.myid
);
935 localStorage
.setItem("variant", variant
);
936 localStorage
.setItem("mycolor", this.mycolor
);
937 localStorage
.setItem("oppid", this.oppid
);
938 localStorage
.setItem("fenStart", this.fenStart
);
939 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
940 localStorage
.setItem("fen", this.vr
.getFen());
942 updateStorage: function() {
943 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
944 localStorage
.setItem("fen", this.vr
.getFen());
946 clearStorage: function() {
947 delete localStorage
["variant"];
948 delete localStorage
["myid"];
949 delete localStorage
["mycolor"];
950 delete localStorage
["oppid"];
951 delete localStorage
["fenStart"];
952 delete localStorage
["fen"];
953 delete localStorage
["moves"];
955 // HACK because mini-css tooltips are persistent after click...
956 getRidOfTooltip: function(elt
) {
957 elt
.style
.visibility
= "hidden";
958 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
960 showSettings: function(e
) {
961 this.getRidOfTooltip(e
.currentTarget
);
962 document
.getElementById("modal-settings").checked
= true;
964 toggleHints: function() {
965 this.hints
= !this.hints
;
966 setCookie("hints", this.hints
? "1" : "0");
968 setColor: function(e
) {
969 this.color
= e
.target
.options
[e
.target
.selectedIndex
].value
;
970 setCookie("color", this.color
);
972 setSound: function(e
) {
973 this.sound
= parseInt(e
.target
.options
[e
.target
.selectedIndex
].value
);
974 setCookie("sound", this.sound
);
976 clickGameSeek: function(e
) {
977 this.getRidOfTooltip(e
.currentTarget
);
978 if (this.mode
== "human")
979 return; //no newgame while playing
982 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
983 delete localStorage
["newgame"]; //cancel game seek
987 this.newGame("human");
989 clickComputerGame: function(e
) {
990 this.getRidOfTooltip(e
.currentTarget
);
991 if (this.mode
== "human")
992 return; //no newgame while playing
993 this.newGame("computer");
995 clickFriendGame: function(e
) {
996 this.getRidOfTooltip(e
.currentTarget
);
997 document
.getElementById("modal-fenedit").checked
= true;
999 resign: function(e
) {
1000 this.getRidOfTooltip(e
.currentTarget
);
1001 if (this.mode
== "human" && this.oppConnected
)
1004 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
1005 } catch (INVALID_STATE_ERR
) {
1006 return; //socket is not ready (and not yet reconnected)
1009 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
1011 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
1012 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
1013 console
.log(fen
); //DEBUG
1014 if (mode
=="human" && !oppId
)
1016 const storageVariant
= localStorage
.getItem("variant");
1017 if (!!storageVariant
&& storageVariant
!== variant
)
1019 alert("Finish your " + storageVariant
+ " game first!");
1022 // Send game request and wait..
1023 localStorage
["newgame"] = variant
;
1025 this.clearStorage(); //in case of
1027 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
1028 } catch (INVALID_STATE_ERR
) {
1029 return; //nothing achieved
1031 if (continuation
!== "reconnect") //TODO: bad HACK...
1033 let modalBox
= document
.getElementById("modal-newgame");
1034 modalBox
.checked
= true;
1035 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1039 this.vr
= new VariantRules(fen
, moves
|| []);
1041 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
1043 this.incheck
= []; //in case of
1044 this.fenStart
= (continuation
? localStorage
.getItem("fenStart") : fen
);
1048 if (!continuation
) //not playing sound on game continuation
1050 if (this.sound
>= 1)
1051 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
1052 document
.getElementById("modal-newgame").checked
= false;
1055 this.oppConnected
= true;
1056 this.mycolor
= color
;
1058 if (!!moves
&& moves
.length
> 0) //imply continuation
1060 const lastMove
= moves
[moves
.length
-1];
1061 this.vr
.undo(lastMove
);
1062 this.incheck
= this.vr
.getCheckSquares(lastMove
);
1063 this.vr
.play(lastMove
, "ingame");
1065 delete localStorage
["newgame"];
1066 this.setStorage(); //in case of interruptions
1068 else if (mode
== "computer")
1070 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
1071 if (this.mycolor
== 'b')
1072 setTimeout(this.playComputerMove
, 500);
1074 //else: against a (IRL) friend: nothing more to do
1076 playComputerMove: function() {
1077 const timeStart
= Date
.now();
1078 const compMove
= this.vr
.getComputerMove();
1079 // (first move) HACK: avoid selecting elements before they appear on page:
1080 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
1081 setTimeout(() => this.play(compMove
, "animate"), delay
);
1083 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1084 getSquareId: function(o
) {
1085 // NOTE: a separator is required to allow any size of board
1086 return "sq-" + o
.x
+ "-" + o
.y
;
1089 getSquareFromId: function(id
) {
1090 let idParts
= id
.split('-');
1091 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
1093 mousedown: function(e
) {
1094 e
= e
|| window
.event
;
1096 let elem
= e
.target
;
1097 while (!ingame
&& elem
!== null)
1099 if (elem
.classList
.contains("game"))
1104 elem
= elem
.parentElement
;
1106 if (!ingame
) //let default behavior (click on button...)
1108 e
.preventDefault(); //disable native drag & drop
1109 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
1111 // Next few lines to center the piece on mouse cursor
1112 let rect
= e
.target
.parentNode
.getBoundingClientRect();
1114 x: rect
.x
+ rect
.width
/2,
1115 y: rect
.y
+ rect
.width
/2,
1116 id: e
.target
.parentNode
.id
1118 this.selectedPiece
= e
.target
.cloneNode();
1119 this.selectedPiece
.style
.position
= "absolute";
1120 this.selectedPiece
.style
.top
= 0;
1121 this.selectedPiece
.style
.display
= "inline-block";
1122 this.selectedPiece
.style
.zIndex
= 3000;
1123 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1124 const iCanPlay
= this.mode
!="idle"
1125 && (this.mode
=="friend" || this.vr
.canIplay(this.mycolor
,startSquare
));
1126 this.possibleMoves
= iCanPlay
? this.vr
.getPossibleMovesFrom(startSquare
) : [];
1127 // Next line add moving piece just after current image
1128 // (required for Crazyhouse reserve)
1129 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1132 mousemove: function(e
) {
1133 if (!this.selectedPiece
)
1135 e
= e
|| window
.event
;
1136 // If there is an active element, move it around
1137 if (!!this.selectedPiece
)
1139 const [offsetX
,offsetY
] = !!e
.clientX
1140 ? [e
.clientX
,e
.clientY
] //desktop browser
1141 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1142 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1143 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1146 mouseup: function(e
) {
1147 if (!this.selectedPiece
)
1149 e
= e
|| window
.event
;
1150 // Read drop target (or parentElement, parentNode... if type == "img")
1151 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1152 const [offsetX
,offsetY
] = !!e
.clientX
1153 ? [e
.clientX
,e
.clientY
]
1154 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1155 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1156 this.selectedPiece
.style
.zIndex
= 3000;
1157 // Next condition: classList.contains(piece) fails because of marks
1158 while (landing
.tagName
== "IMG")
1159 landing
= landing
.parentNode
;
1160 if (this.start
.id
== landing
.id
)
1162 // A click: selectedPiece and possibleMoves are already filled
1165 // OK: process move attempt
1166 let endSquare
= this.getSquareFromId(landing
.id
);
1167 let moves
= this.findMatchingMoves(endSquare
);
1168 this.possibleMoves
= [];
1169 if (moves
.length
> 1)
1170 this.choices
= moves
;
1171 else if (moves
.length
==1)
1172 this.play(moves
[0]);
1173 // Else: impossible move
1174 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1175 delete this.selectedPiece
;
1176 this.selectedPiece
= null;
1178 findMatchingMoves: function(endSquare
) {
1179 // Run through moves list and return the matching set (if promotions...)
1181 this.possibleMoves
.forEach(function(m
) {
1182 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1187 animateMove: function(move) {
1188 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1189 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1190 let rectStart
= startSquare
.getBoundingClientRect();
1191 let rectEnd
= endSquare
.getBoundingClientRect();
1192 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1194 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1195 // HACK for animation (with positive translate, image slides "under background")
1196 // Possible improvement: just alter squares on the piece's way...
1197 squares
= document
.getElementsByClassName("board");
1198 for (let i
=0; i
<squares
.length
; i
++)
1200 let square
= squares
.item(i
);
1201 if (square
.id
!= this.getSquareId(move.start
))
1202 square
.style
.zIndex
= "-1";
1204 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1205 translation
.y
+ "px)";
1206 movingPiece
.style
.transitionDuration
= "0.2s";
1207 movingPiece
.style
.zIndex
= "3000";
1209 for (let i
=0; i
<squares
.length
; i
++)
1210 squares
.item(i
).style
.zIndex
= "auto";
1211 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1215 play: function(move, programmatic
) {
1218 // Navigate after game is over
1219 if (this.cursor
>= this.vr
.moves
.length
)
1220 return; //already at the end
1221 move = this.vr
.moves
[this.cursor
++];
1223 if (!!programmatic
) //computer or human opponent
1225 this.animateMove(move);
1228 // Not programmatic, or animation is over
1229 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1230 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1231 if (this.sound
== 2)
1232 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
1233 if (this.mode
!= "idle")
1235 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1236 this.vr
.play(move, "ingame");
1240 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1241 this.$forceUpdate(); //TODO: ?!
1243 if (this.mode
== "human")
1244 this.updateStorage(); //after our moves and opponent moves
1245 if (this.mode
!= "idle")
1247 const eog
= this.vr
.checkGameOver();
1251 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1252 setTimeout(this.playComputerMove
, 500);
1255 // Navigate after game is over
1256 if (this.cursor
== 0)
1257 return; //already at the beginning
1258 if (this.cursor
== this.vr
.moves
.length
)
1259 this.incheck
= []; //in case of...
1260 const move = this.vr
.moves
[--this.cursor
];
1261 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1262 this.$forceUpdate(); //TODO: ?!
1264 undoInGame: function() {
1265 const lm
= this.vr
.lastMove
;