278e07824ed9066db980f8a0d5492f2d387cb289
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
] = [V
.size
.x
,V
.size
.y
];
28 const smallScreen
= (window
.innerWidth
<= 420);
29 // Precompute hints squares to facilitate rendering
30 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
31 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
32 // Also precompute in-check squares
33 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
34 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
35 let elementArray
= [];
40 on: { click: this.clickGameSeek
},
41 attrs: { "aria-label": 'New online game' },
44 "bottom": true, //display below
46 "playing": this.mode
== "human",
50 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
52 if (["idle","computer"].includes(this.mode
))
57 on: { click: this.clickComputerGame
},
58 attrs: { "aria-label": 'New game VS computer' },
62 "playing": this.mode
== "computer",
66 [h('i', { 'class': { "material-icons": true } }, "computer")])
69 if (["idle","friend"].includes(this.mode
))
74 on: { click: this.clickFriendGame
},
75 attrs: { "aria-label": 'New IRL game' },
79 "playing": this.mode
== "friend",
83 [h('i', { 'class': { "material-icons": true } }, "people")])
88 const square00
= document
.getElementById("sq-0-0");
89 const squareWidth
= !!square00
90 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
92 const settingsBtnElt
= document
.getElementById("settingsBtn");
93 const indicWidth
= !!settingsBtnElt
//-2 for border:
94 ? parseFloat(window
.getComputedStyle(settingsBtnElt
).height
.slice(0,-2)) - 2
95 : (smallScreen
? 31 : 37);
96 if (this.mode
== "human")
98 let connectedIndic
= h(
102 "topindicator": true,
104 "connected": this.oppConnected
,
105 "disconnected": !this.oppConnected
,
108 "width": indicWidth
+ "px",
109 "height": indicWidth
+ "px",
113 elementArray
.push(connectedIndic
);
119 "topindicator": true,
121 "white-turn": this.vr
.turn
=="w",
122 "black-turn": this.vr
.turn
=="b",
125 "width": indicWidth
+ "px",
126 "height": indicWidth
+ "px",
130 elementArray
.push(turnIndic
);
134 on: { click: this.showSettings
},
136 "aria-label": 'Settings',
141 "topindicator": true,
143 "settings-btn": !smallScreen
,
144 "settings-btn-small": smallScreen
,
147 [h('i', { 'class': { "material-icons": true } }, "settings")]
149 elementArray
.push(settingsBtn
);
150 let choices
= h('div',
152 attrs: { "id": "choices" },
153 'class': { 'row': true },
155 "display": this.choices
.length
>0?"block":"none",
156 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
157 "width": (this.choices
.length
* squareWidth
) + "px",
158 "height": squareWidth
+ "px",
161 this.choices
.map( m
=> { //a "choice" is a move
166 ['board'+sizeY
]: true,
169 'width': (100/this.choices
.length
) + "%",
170 'padding-bottom': (100/this.choices
.length
) + "%",
175 attrs: { "src": '/images/pieces/' +
176 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
177 'class': { 'choice-piece': true },
178 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
184 // Create board element (+ reserves if needed by variant or mode)
185 const lm
= this.vr
.lastMove
;
186 const showLight
= this.hints
&&
187 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
188 let gameDiv
= h('div',
190 'class': { 'game': true },
192 [_
.range(sizeX
).map(i
=> {
193 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
200 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
202 _
.range(sizeY
).map(j
=> {
203 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
205 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
213 'ghost': !!this.selectedPiece
214 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
217 src: "/images/pieces/" +
218 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
224 if (this.hints
&& hintSquares
[ci
][cj
])
234 src: "/images/mark.svg",
245 ['board'+sizeY
]: true,
246 'light-square': (i
+j
)%2==0,
247 'dark-square': (i
+j
)%2==1,
249 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
250 'incheck': showLight
&& incheckSq
[ci
][cj
],
253 id: this.getSquareId({x:ci
,y:cj
}),
262 if (this.mode
!= "idle")
267 on: { click: this.resign
},
268 attrs: { "aria-label": 'Resign' },
272 "small": smallScreen
,
275 [h('i', { 'class': { "material-icons": true } }, "flag")])
278 else if (this.vr
.moves
.length
> 0)
280 // A game finished, and another is not started yet: allow navigation
281 actionArray
= actionArray
.concat([
284 on: { click: e
=> this.undo() },
285 attrs: { "aria-label": 'Undo' },
287 "small": smallScreen
,
291 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
294 on: { click: e
=> this.play() },
295 attrs: { "aria-label": 'Play' },
296 "class": { "small": smallScreen
},
298 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
302 if (this.mode
== "friend")
304 actionArray
= actionArray
.concat(
308 on: { click: this.undoInGame
},
309 attrs: { "aria-label": 'Undo' },
311 "small": smallScreen
,
315 [h('i', { 'class': { "material-icons": true } }, "undo")]
319 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
320 attrs: { "aria-label": 'Flip' },
321 "class": { "small": smallScreen
},
323 [h('i', { 'class': { "material-icons": true } }, "cached")]
327 elementArray
.push(gameDiv
);
328 if (!!this.vr
.reserve
)
330 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
331 let myReservePiecesArray
= [];
332 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
334 myReservePiecesArray
.push(h('div',
336 'class': {'board':true, ['board'+sizeY
]:true},
337 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
342 'class': {"piece":true},
344 "src": "/images/pieces/" +
345 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
349 {"class": { "reserve-count": true } },
350 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
354 let oppReservePiecesArray
= [];
355 const oppCol
= this.vr
.getOppCol(this.mycolor
);
356 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
358 oppReservePiecesArray
.push(h('div',
360 'class': {'board':true, ['board'+sizeY
]:true},
361 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
366 'class': {"piece":true},
368 "src": "/images/pieces/" +
369 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
373 {"class": { "reserve-count": true } },
374 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
378 let reserves
= h('div',
390 "reserve-row-1": true,
396 { 'class': { 'row': true }},
397 oppReservePiecesArray
401 elementArray
.push(reserves
);
403 const eogMessage
= this.getEndgameMessage(this.score
);
407 attrs: { "id": "modal-eog", type: "checkbox" },
408 "class": { "modal": true },
412 attrs: { "role": "dialog", "aria-labelledby": "eogMessage" },
417 "class": { "card": true, "smallpad": true },
422 attrs: { "for": "modal-eog" },
423 "class": { "modal-close": true },
428 attrs: { "id": "eogMessage" },
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": "newGameTxt" },
454 "class": { "card": true, "smallpad": true },
459 attrs: { "id": "close-newgame", "for": "modal-newgame" },
460 "class": { "modal-close": true },
465 attrs: { "id": "newGameTxt" },
466 "class": { "section": true },
467 domProps: { innerHTML: "New game" },
472 "class": { "section": true },
473 domProps: { innerHTML: "Waiting for opponent..." },
481 elementArray
= elementArray
.concat(modalNewgame
);
482 const modalFenEdit
= [
485 attrs: { "id": "modal-fenedit", type: "checkbox" },
486 "class": { "modal": true },
490 attrs: { "role": "dialog", "aria-labelledby": "titleFenedit" },
495 "class": { "card": true, "smallpad": true },
500 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
501 "class": { "modal-close": true },
506 attrs: { "id": "titleFenedit" },
507 "class": { "section": true },
508 domProps: { innerHTML: "Position + flags (FEN):" },
516 value: VariantRules
.GenRandInitFen(),
524 const fen
= document
.getElementById("input-fen").value
;
525 document
.getElementById("modal-fenedit").checked
= false;
526 this.newGame("friend", fen
);
529 domProps: { innerHTML: "Ok" },
536 document
.getElementById("input-fen").value
=
537 VariantRules
.GenRandInitFen();
540 domProps: { innerHTML: "Random" },
548 elementArray
= elementArray
.concat(modalFenEdit
);
549 const modalSettings
= [
552 attrs: { "id": "modal-settings", type: "checkbox" },
553 "class": { "modal": true },
557 attrs: { "role": "dialog", "aria-labelledby": "settingsTitle" },
562 "class": { "card": true, "smallpad": true },
567 attrs: { "id": "close-settings", "for": "modal-settings" },
568 "class": { "modal-close": true },
573 attrs: { "id": "settingsTitle" },
574 "class": { "section": true },
575 domProps: { innerHTML: "Preferences" },
581 //h('legend', { domProps: { innerHTML: "Legend title" } }),
584 attrs: { for: "setHints" },
585 domProps: { innerHTML: "Show hints?" },
595 on: { "change": this.toggleHints
},
605 attrs: { for: "selectColor" },
606 domProps: { innerHTML: "Board colors" },
611 attrs: { "id": "selectColor" },
612 on: { "change": this.setColor
},
621 attrs: { "selected": this.color
=="lichess" },
630 attrs: { "selected": this.color
=="chesscom" },
636 "value": "chesstempo",
639 attrs: { "selected": this.color
=="chesstempo" },
651 attrs: { for: "selectSound" },
652 domProps: { innerHTML: "Play sounds?" },
657 attrs: { "id": "selectSound" },
658 on: { "change": this.setSound
},
667 attrs: { "selected": this.sound
==0 },
676 attrs: { "selected": this.sound
==1 },
685 attrs: { "selected": this.sound
==2 },
697 elementArray
= elementArray
.concat(modalSettings
);
698 const actions
= h('div',
700 attrs: { "id": "actions" },
701 'class': { 'text-center': true },
705 elementArray
.push(actions
);
706 if (this.score
!= "*")
711 attrs: { id: "pgn-div" },
712 "class": { "section-content": true },
725 attrs: { id: "pgn-game" },
726 domProps: { innerHTML: this.pgnTxt
}
731 attrs: { "id": "downloadBtn" },
732 on: { click: this.download
},
733 domProps: { innerHTML: "Download game" },
740 else if (this.mode
!= "idle")
746 attrs: { id: "fen-div" },
747 "class": { "section-content": true },
752 attrs: { id: "fen-string" },
753 domProps: { innerHTML: this.vr
.getFen() }
766 "col-md-offset-2":true,
768 "col-lg-offset-3":true,
770 // NOTE: click = mousedown + mouseup
772 mousedown: this.mousedown
,
773 mousemove: this.mousemove
,
774 mouseup: this.mouseup
,
775 touchstart: this.mousedown
,
776 touchmove: this.mousemove
,
777 touchend: this.mouseup
,
783 created: function() {
784 const url
= socketUrl
;
785 const continuation
= (localStorage
.getItem("variant") === variant
);
786 this.myid
= (continuation
? localStorage
.getItem("myid") : getRandString());
789 // HACK: play a small silent sound to allow "new game" sound later
790 // if tab not focused (TODO: does it really work ?!)
791 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
793 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
794 const socketOpenListener
= () => {
797 const fen
= localStorage
.getItem("fen");
798 const mycolor
= localStorage
.getItem("mycolor");
799 const oppid
= localStorage
.getItem("oppid");
800 const moves
= JSON
.parse(localStorage
.getItem("moves"));
801 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
802 // Send ping to server (answer pong if opponent is connected)
803 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
805 else if (localStorage
.getItem("newgame") === variant
)
807 // New game request has been cancelled on disconnect
808 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
811 const socketMessageListener
= msg
=> {
812 const data
= JSON
.parse(msg
.data
);
816 // We opened another tab on the same game
819 alert("Already playing a game in this variant on another tab!");
821 case "newgame": //opponent found
822 // oppid: opponent socket ID
823 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
825 case "newmove": //..he played!
826 this.play(data
.move, "animate");
828 case "pong": //received if we sent a ping (game still alive on our side)
829 this.oppConnected
= true;
830 const L
= this.vr
.moves
.length
;
831 // Send our "last state" informations to opponent
832 this.conn
.send(JSON
.stringify({
835 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
839 case "lastate": //got opponent infos about last move (we might have resigned)
840 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
843 this.conn
.send(JSON
.stringify({
850 else if (data
.movesCount
< 0)
853 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
855 else if (data
.movesCount
< this.vr
.moves
.length
)
857 // We must tell last move to opponent
858 const L
= this.vr
.moves
.length
;
859 this.conn
.send(JSON
.stringify({
862 lastMove:this.vr
.moves
[L
-1],
866 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
867 this.play(data
.lastMove
, "animate");
869 case "resign": //..you won!
870 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
872 // TODO: also use (dis)connect info to count online players?
875 if (this.mode
== "human" && this.oppid
== data
.id
)
876 this.oppConnected
= (data
.code
== "connect");
880 const socketCloseListener
= () => {
881 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
882 this.conn
.addEventListener('open', socketOpenListener
);
883 this.conn
.addEventListener('message', socketMessageListener
);
884 this.conn
.addEventListener('close', socketCloseListener
);
886 this.conn
.onopen
= socketOpenListener
;
887 this.conn
.onmessage
= socketMessageListener
;
888 this.conn
.onclose
= socketCloseListener
;
889 // Listen to keyboard left/right to navigate in game
890 document
.onkeydown
= event
=> {
891 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
892 && [37,39].includes(event
.keyCode
))
894 event
.preventDefault();
895 if (event
.keyCode
== 37) //Back
903 download: function() {
904 let content
= document
.getElementById("pgn-game").innerHTML
;
905 content
= content
.replace(/<br>/g, "\n");
906 // Prepare and trigger download link
907 let downloadAnchor
= document
.getElementById("download");
908 downloadAnchor
.setAttribute("download", "game.pgn");
909 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
910 encodeURIComponent(content
);
911 downloadAnchor
.click();
913 endGame: function(score
) {
915 let modalBox
= document
.getElementById("modal-eog");
916 modalBox
.checked
= true;
917 // Variants may have special PGN structure (so next function isn't defined here)
918 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
919 setTimeout(() => { modalBox
.checked
= false; }, 2000);
920 if (this.mode
== "human")
923 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
926 getEndgameMessage: function(score
) {
927 let eogMessage
= "Unfinished";
931 eogMessage
= "White win";
934 eogMessage
= "Black win";
942 setStorage: function() {
943 localStorage
.setItem("myid", this.myid
);
944 localStorage
.setItem("variant", variant
);
945 localStorage
.setItem("mycolor", this.mycolor
);
946 localStorage
.setItem("oppid", this.oppid
);
947 localStorage
.setItem("fenStart", this.fenStart
);
948 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
949 localStorage
.setItem("fen", this.vr
.getFen());
951 updateStorage: function() {
952 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
953 localStorage
.setItem("fen", this.vr
.getFen());
955 clearStorage: function() {
956 delete localStorage
["variant"];
957 delete localStorage
["myid"];
958 delete localStorage
["mycolor"];
959 delete localStorage
["oppid"];
960 delete localStorage
["fenStart"];
961 delete localStorage
["fen"];
962 delete localStorage
["moves"];
964 // HACK because mini-css tooltips are persistent after click...
965 getRidOfTooltip: function(elt
) {
966 elt
.style
.visibility
= "hidden";
967 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
969 showSettings: function(e
) {
970 this.getRidOfTooltip(e
.currentTarget
);
971 document
.getElementById("modal-settings").checked
= true;
973 toggleHints: function() {
974 this.hints
= !this.hints
;
975 setCookie("hints", this.hints
? "1" : "0");
977 setColor: function(e
) {
978 this.color
= e
.target
.options
[e
.target
.selectedIndex
].value
;
979 setCookie("color", this.color
);
981 setSound: function(e
) {
982 this.sound
= parseInt(e
.target
.options
[e
.target
.selectedIndex
].value
);
983 setCookie("sound", this.sound
);
985 clickGameSeek: function(e
) {
986 this.getRidOfTooltip(e
.currentTarget
);
987 if (this.mode
== "human")
988 return; //no newgame while playing
991 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
992 delete localStorage
["newgame"]; //cancel game seek
996 this.newGame("human");
998 clickComputerGame: function(e
) {
999 this.getRidOfTooltip(e
.currentTarget
);
1000 if (this.mode
== "human")
1001 return; //no newgame while playing
1002 this.newGame("computer");
1004 clickFriendGame: function(e
) {
1005 this.getRidOfTooltip(e
.currentTarget
);
1006 document
.getElementById("modal-fenedit").checked
= true;
1008 resign: function(e
) {
1009 this.getRidOfTooltip(e
.currentTarget
);
1010 if (this.mode
== "human" && this.oppConnected
)
1013 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
1014 } catch (INVALID_STATE_ERR
) {
1015 return; //socket is not ready (and not yet reconnected)
1018 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
1020 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
1021 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
1022 console
.log(fen
); //DEBUG
1023 if (mode
=="human" && !oppId
)
1025 const storageVariant
= localStorage
.getItem("variant");
1026 if (!!storageVariant
&& storageVariant
!== variant
)
1028 alert("Finish your " + storageVariant
+ " game first!");
1031 // Send game request and wait..
1032 localStorage
["newgame"] = variant
;
1034 this.clearStorage(); //in case of
1036 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
1037 } catch (INVALID_STATE_ERR
) {
1038 return; //nothing achieved
1040 if (continuation
!== "reconnect") //TODO: bad HACK...
1042 let modalBox
= document
.getElementById("modal-newgame");
1043 modalBox
.checked
= true;
1044 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1048 this.vr
= new VariantRules(fen
, moves
|| []);
1050 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
1052 this.incheck
= []; //in case of
1053 this.fenStart
= (continuation
? localStorage
.getItem("fenStart") : fen
);
1057 if (!continuation
) //not playing sound on game continuation
1059 if (this.sound
>= 1)
1060 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
1061 document
.getElementById("modal-newgame").checked
= false;
1064 this.oppConnected
= !continuation
;
1065 this.mycolor
= color
;
1067 if (!!moves
&& moves
.length
> 0) //imply continuation
1069 const lastMove
= moves
[moves
.length
-1];
1070 this.vr
.undo(lastMove
);
1071 this.incheck
= this.vr
.getCheckSquares(lastMove
);
1072 this.vr
.play(lastMove
, "ingame");
1074 delete localStorage
["newgame"];
1075 this.setStorage(); //in case of interruptions
1077 else if (mode
== "computer")
1079 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
1080 if (this.mycolor
== 'b')
1081 setTimeout(this.playComputerMove
, 500);
1083 //else: against a (IRL) friend: nothing more to do
1085 playComputerMove: function() {
1086 const timeStart
= Date
.now();
1087 const compMove
= this.vr
.getComputerMove();
1088 // (first move) HACK: avoid selecting elements before they appear on page:
1089 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
1091 if (this.mode
== "computer") //Warning: mode could have changed!
1092 this.play(compMove
, "animate")
1095 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1096 getSquareId: function(o
) {
1097 // NOTE: a separator is required to allow any size of board
1098 return "sq-" + o
.x
+ "-" + o
.y
;
1101 getSquareFromId: function(id
) {
1102 let idParts
= id
.split('-');
1103 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
1105 mousedown: function(e
) {
1106 e
= e
|| window
.event
;
1108 let elem
= e
.target
;
1109 while (!ingame
&& elem
!== null)
1111 if (elem
.classList
.contains("game"))
1116 elem
= elem
.parentElement
;
1118 if (!ingame
) //let default behavior (click on button...)
1120 e
.preventDefault(); //disable native drag & drop
1121 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
1123 // Next few lines to center the piece on mouse cursor
1124 let rect
= e
.target
.parentNode
.getBoundingClientRect();
1126 x: rect
.x
+ rect
.width
/2,
1127 y: rect
.y
+ rect
.width
/2,
1128 id: e
.target
.parentNode
.id
1130 this.selectedPiece
= e
.target
.cloneNode();
1131 this.selectedPiece
.style
.position
= "absolute";
1132 this.selectedPiece
.style
.top
= 0;
1133 this.selectedPiece
.style
.display
= "inline-block";
1134 this.selectedPiece
.style
.zIndex
= 3000;
1135 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1136 const iCanPlay
= this.mode
!="idle"
1137 && (this.mode
=="friend" || this.vr
.canIplay(this.mycolor
,startSquare
));
1138 this.possibleMoves
= iCanPlay
? this.vr
.getPossibleMovesFrom(startSquare
) : [];
1139 // Next line add moving piece just after current image
1140 // (required for Crazyhouse reserve)
1141 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1144 mousemove: function(e
) {
1145 if (!this.selectedPiece
)
1147 e
= e
|| window
.event
;
1148 // If there is an active element, move it around
1149 if (!!this.selectedPiece
)
1151 const [offsetX
,offsetY
] = !!e
.clientX
1152 ? [e
.clientX
,e
.clientY
] //desktop browser
1153 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1154 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1155 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1158 mouseup: function(e
) {
1159 if (!this.selectedPiece
)
1161 e
= e
|| window
.event
;
1162 // Read drop target (or parentElement, parentNode... if type == "img")
1163 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1164 const [offsetX
,offsetY
] = !!e
.clientX
1165 ? [e
.clientX
,e
.clientY
]
1166 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1167 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1168 this.selectedPiece
.style
.zIndex
= 3000;
1169 // Next condition: classList.contains(piece) fails because of marks
1170 while (landing
.tagName
== "IMG")
1171 landing
= landing
.parentNode
;
1172 if (this.start
.id
== landing
.id
)
1174 // A click: selectedPiece and possibleMoves are already filled
1177 // OK: process move attempt
1178 let endSquare
= this.getSquareFromId(landing
.id
);
1179 let moves
= this.findMatchingMoves(endSquare
);
1180 this.possibleMoves
= [];
1181 if (moves
.length
> 1)
1182 this.choices
= moves
;
1183 else if (moves
.length
==1)
1184 this.play(moves
[0]);
1185 // Else: impossible move
1186 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1187 delete this.selectedPiece
;
1188 this.selectedPiece
= null;
1190 findMatchingMoves: function(endSquare
) {
1191 // Run through moves list and return the matching set (if promotions...)
1193 this.possibleMoves
.forEach(function(m
) {
1194 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1199 animateMove: function(move) {
1200 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1201 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1202 let rectStart
= startSquare
.getBoundingClientRect();
1203 let rectEnd
= endSquare
.getBoundingClientRect();
1204 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1206 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1207 // HACK for animation (with positive translate, image slides "under background")
1208 // Possible improvement: just alter squares on the piece's way...
1209 squares
= document
.getElementsByClassName("board");
1210 for (let i
=0; i
<squares
.length
; i
++)
1212 let square
= squares
.item(i
);
1213 if (square
.id
!= this.getSquareId(move.start
))
1214 square
.style
.zIndex
= "-1";
1216 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1217 translation
.y
+ "px)";
1218 movingPiece
.style
.transitionDuration
= "0.2s";
1219 movingPiece
.style
.zIndex
= "3000";
1221 for (let i
=0; i
<squares
.length
; i
++)
1222 squares
.item(i
).style
.zIndex
= "auto";
1223 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1227 play: function(move, programmatic
) {
1230 // Navigate after game is over
1231 if (this.cursor
>= this.vr
.moves
.length
)
1232 return; //already at the end
1233 move = this.vr
.moves
[this.cursor
++];
1235 if (!!programmatic
) //computer or human opponent
1237 this.animateMove(move);
1240 // Not programmatic, or animation is over
1241 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1242 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1243 if (this.sound
== 2)
1244 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
1245 if (this.mode
!= "idle")
1247 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1248 this.vr
.play(move, "ingame");
1252 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1253 this.$forceUpdate(); //TODO: ?!
1255 if (this.mode
== "human")
1256 this.updateStorage(); //after our moves and opponent moves
1257 if (this.mode
!= "idle")
1259 const eog
= this.vr
.checkGameOver();
1263 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1264 setTimeout(this.playComputerMove
, 500);
1267 // Navigate after game is over
1268 if (this.cursor
== 0)
1269 return; //already at the beginning
1270 if (this.cursor
== this.vr
.moves
.length
)
1271 this.incheck
= []; //in case of...
1272 const move = this.vr
.moves
[--this.cursor
];
1273 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1274 this.$forceUpdate(); //TODO: ?!
1276 undoInGame: function() {
1277 const lm
= this.vr
.lastMove
;