1 // Game logic on a variant page
2 Vue
.component('my-game', {
6 vr: null, //object to check moves, store them, FEN..
8 possibleMoves: [], //filled after each valid click/dragstart
9 choices: [], //promotion pieces, or checkered captures... (as moves)
10 start: {}, //pixels coordinates + id of starting square (click or drag)
11 selectedPiece: null, //moving piece (or clicked piece)
12 conn: null, //socket connection
13 score: "*", //'*' means 'unfinished'
14 mode: "idle", //human, friend, computer or idle (when not playing)
15 oppid: "", //opponent ID in case of HH game
21 hints: (getCookie("hints") === "1" ? true : false),
22 color: getCookie("color", "lichess"), //lichess, chesscom or chesstempo
23 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
24 sound: parseInt(getCookie("sound", "2")),
28 problem: function(p
, pp
) {
29 // 'problem' prop changed: update board state
30 // TODO: FEN + turn + flags + rappel instructions / solution on click sous l'échiquier
31 // TODO: trouver moyen de passer la situation des reserves pour Crazyhouse,
32 // et l'état des captures pour Grand... bref compléter le descriptif de l'état.
33 this.newGame("problem", p
.fen
, p
.fen
.split(" ")[2]);
37 const [sizeX
,sizeY
] = [V
.size
.x
,V
.size
.y
];
38 const smallScreen
= (window
.innerWidth
<= 420);
39 // Precompute hints squares to facilitate rendering
40 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
41 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
42 // Also precompute in-check squares
43 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
44 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
45 let elementArray
= [];
50 on: { click: this.clickGameSeek
},
51 attrs: { "aria-label": 'New online game' },
54 "bottom": true, //display below
56 "playing": this.mode
== "human",
60 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
62 if (["idle","computer"].includes(this.mode
))
67 on: { click: this.clickComputerGame
},
68 attrs: { "aria-label": 'New game VS computer' },
72 "playing": this.mode
== "computer",
76 [h('i', { 'class': { "material-icons": true } }, "computer")])
79 if (["idle","friend"].includes(this.mode
))
84 on: { click: this.clickFriendGame
},
85 attrs: { "aria-label": 'New IRL game' },
89 "playing": this.mode
== "friend",
93 [h('i', { 'class': { "material-icons": true } }, "people")])
98 const square00
= document
.getElementById("sq-0-0");
99 const squareWidth
= !!square00
100 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
102 const settingsBtnElt
= document
.getElementById("settingsBtn");
103 const indicWidth
= !!settingsBtnElt
//-2 for border:
104 ? parseFloat(window
.getComputedStyle(settingsBtnElt
).height
.slice(0,-2)) - 2
105 : (smallScreen
? 31 : 37);
106 if (this.mode
== "human")
108 let connectedIndic
= h(
112 "topindicator": true,
114 "connected": this.oppConnected
,
115 "disconnected": !this.oppConnected
,
118 "width": indicWidth
+ "px",
119 "height": indicWidth
+ "px",
123 elementArray
.push(connectedIndic
);
129 "topindicator": true,
131 "white-turn": this.vr
.turn
=="w",
132 "black-turn": this.vr
.turn
=="b",
135 "width": indicWidth
+ "px",
136 "height": indicWidth
+ "px",
140 elementArray
.push(turnIndic
);
144 on: { click: this.showSettings
},
146 "aria-label": 'Settings',
151 "topindicator": true,
153 "settings-btn": !smallScreen
,
154 "settings-btn-small": smallScreen
,
157 [h('i', { 'class': { "material-icons": true } }, "settings")]
159 elementArray
.push(settingsBtn
);
160 let choices
= h('div',
162 attrs: { "id": "choices" },
163 'class': { 'row': true },
165 "display": this.choices
.length
>0?"block":"none",
166 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
167 "width": (this.choices
.length
* squareWidth
) + "px",
168 "height": squareWidth
+ "px",
171 this.choices
.map( m
=> { //a "choice" is a move
176 ['board'+sizeY
]: true,
179 'width': (100/this.choices
.length
) + "%",
180 'padding-bottom': (100/this.choices
.length
) + "%",
185 attrs: { "src": '/images/pieces/' +
186 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
187 'class': { 'choice-piece': true },
188 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
194 // Create board element (+ reserves if needed by variant or mode)
195 const lm
= this.vr
.lastMove
;
196 const showLight
= this.hints
&&
197 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
198 let gameDiv
= h('div',
200 'class': { 'game': true },
202 [_
.range(sizeX
).map(i
=> {
203 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
210 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
212 _
.range(sizeY
).map(j
=> {
213 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
215 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
223 'ghost': !!this.selectedPiece
224 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
227 src: "/images/pieces/" +
228 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
234 if (this.hints
&& hintSquares
[ci
][cj
])
244 src: "/images/mark.svg",
255 ['board'+sizeY
]: true,
256 'light-square': (i
+j
)%2==0,
257 'dark-square': (i
+j
)%2==1,
259 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
260 'incheck': showLight
&& incheckSq
[ci
][cj
],
263 id: this.getSquareId({x:ci
,y:cj
}),
272 if (this.mode
!= "idle")
277 on: { click: this.resign
},
278 attrs: { "aria-label": 'Resign' },
282 "small": smallScreen
,
285 [h('i', { 'class': { "material-icons": true } }, "flag")])
288 else if (this.vr
.moves
.length
> 0)
290 // A game finished, and another is not started yet: allow navigation
291 actionArray
= actionArray
.concat([
294 on: { click: e
=> this.undo() },
295 attrs: { "aria-label": 'Undo' },
297 "small": smallScreen
,
301 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
304 on: { click: e
=> this.play() },
305 attrs: { "aria-label": 'Play' },
306 "class": { "small": smallScreen
},
308 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
312 if (this.mode
== "friend")
314 actionArray
= actionArray
.concat(
318 on: { click: this.undoInGame
},
319 attrs: { "aria-label": 'Undo' },
321 "small": smallScreen
,
325 [h('i', { 'class': { "material-icons": true } }, "undo")]
329 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
330 attrs: { "aria-label": 'Flip' },
331 "class": { "small": smallScreen
},
333 [h('i', { 'class': { "material-icons": true } }, "cached")]
337 elementArray
.push(gameDiv
);
338 if (!!this.vr
.reserve
)
340 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
341 let myReservePiecesArray
= [];
342 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
344 myReservePiecesArray
.push(h('div',
346 'class': {'board':true, ['board'+sizeY
]:true},
347 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
352 'class': {"piece":true},
354 "src": "/images/pieces/" +
355 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
359 {"class": { "reserve-count": true } },
360 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
364 let oppReservePiecesArray
= [];
365 const oppCol
= this.vr
.getOppCol(this.mycolor
);
366 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
368 oppReservePiecesArray
.push(h('div',
370 'class': {'board':true, ['board'+sizeY
]:true},
371 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
376 'class': {"piece":true},
378 "src": "/images/pieces/" +
379 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
383 {"class": { "reserve-count": true } },
384 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
388 let reserves
= h('div',
400 "reserve-row-1": true,
406 { 'class': { 'row': true }},
407 oppReservePiecesArray
411 elementArray
.push(reserves
);
413 const eogMessage
= this.getEndgameMessage(this.score
);
417 attrs: { "id": "modal-eog", type: "checkbox" },
418 "class": { "modal": true },
422 attrs: { "role": "dialog", "aria-labelledby": "eogMessage" },
427 "class": { "card": true, "smallpad": true },
432 attrs: { "for": "modal-eog" },
433 "class": { "modal-close": true },
438 attrs: { "id": "eogMessage" },
439 "class": { "section": true },
440 domProps: { innerHTML: eogMessage
},
448 elementArray
= elementArray
.concat(modalEog
);
450 // NOTE: this modal could be in Pug view (no usage of Vue functions or variables)
451 const modalNewgame
= [
454 attrs: { "id": "modal-newgame", type: "checkbox" },
455 "class": { "modal": true },
459 attrs: { "role": "dialog", "aria-labelledby": "newGameTxt" },
464 "class": { "card": true, "smallpad": true },
469 attrs: { "id": "close-newgame", "for": "modal-newgame" },
470 "class": { "modal-close": true },
475 attrs: { "id": "newGameTxt" },
476 "class": { "section": true },
477 domProps: { innerHTML: "New game" },
482 "class": { "section": true },
483 domProps: { innerHTML: "Waiting for opponent..." },
491 elementArray
= elementArray
.concat(modalNewgame
);
492 const modalFenEdit
= [
495 attrs: { "id": "modal-fenedit", type: "checkbox" },
496 "class": { "modal": true },
500 attrs: { "role": "dialog", "aria-labelledby": "titleFenedit" },
505 "class": { "card": true, "smallpad": true },
510 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
511 "class": { "modal-close": true },
516 attrs: { "id": "titleFenedit" },
517 "class": { "section": true },
518 domProps: { innerHTML: "Position + flags (FEN):" },
526 value: VariantRules
.GenRandInitFen(),
534 const fen
= document
.getElementById("input-fen").value
;
535 document
.getElementById("modal-fenedit").checked
= false;
536 this.newGame("friend", fen
);
539 domProps: { innerHTML: "Ok" },
546 document
.getElementById("input-fen").value
=
547 VariantRules
.GenRandInitFen();
550 domProps: { innerHTML: "Random" },
558 elementArray
= elementArray
.concat(modalFenEdit
);
559 const modalSettings
= [
562 attrs: { "id": "modal-settings", type: "checkbox" },
563 "class": { "modal": true },
567 attrs: { "role": "dialog", "aria-labelledby": "settingsTitle" },
572 "class": { "card": true, "smallpad": true },
577 attrs: { "id": "close-settings", "for": "modal-settings" },
578 "class": { "modal-close": true },
583 attrs: { "id": "settingsTitle" },
584 "class": { "section": true },
585 domProps: { innerHTML: "Preferences" },
591 //h('legend', { domProps: { innerHTML: "Legend title" } }),
594 attrs: { for: "setHints" },
595 domProps: { innerHTML: "Show hints?" },
605 on: { "change": this.toggleHints
},
615 attrs: { for: "selectColor" },
616 domProps: { innerHTML: "Board colors" },
621 attrs: { "id": "selectColor" },
622 on: { "change": this.setColor
},
631 attrs: { "selected": this.color
=="lichess" },
640 attrs: { "selected": this.color
=="chesscom" },
646 "value": "chesstempo",
649 attrs: { "selected": this.color
=="chesstempo" },
661 attrs: { for: "selectSound" },
662 domProps: { innerHTML: "Play sounds?" },
667 attrs: { "id": "selectSound" },
668 on: { "change": this.setSound
},
677 attrs: { "selected": this.sound
==0 },
686 attrs: { "selected": this.sound
==1 },
695 attrs: { "selected": this.sound
==2 },
707 elementArray
= elementArray
.concat(modalSettings
);
708 const actions
= h('div',
710 attrs: { "id": "actions" },
711 'class': { 'text-center': true },
715 elementArray
.push(actions
);
716 if (this.score
!= "*")
721 attrs: { id: "pgn-div" },
722 "class": { "section-content": true },
735 attrs: { id: "pgn-game" },
736 domProps: { innerHTML: this.pgnTxt
}
741 attrs: { "id": "downloadBtn" },
742 on: { click: this.download
},
743 domProps: { innerHTML: "Download game" },
750 else if (this.mode
!= "idle")
756 attrs: { id: "fen-div" },
757 "class": { "section-content": true },
762 attrs: { id: "fen-string" },
763 domProps: { innerHTML: this.vr
.getFen() }
776 "col-md-offset-2":true,
778 "col-lg-offset-3":true,
780 // NOTE: click = mousedown + mouseup
782 mousedown: this.mousedown
,
783 mousemove: this.mousemove
,
784 mouseup: this.mouseup
,
785 touchstart: this.mousedown
,
786 touchmove: this.mousemove
,
787 touchend: this.mouseup
,
793 created: function() {
794 const url
= socketUrl
;
795 const continuation
= (localStorage
.getItem("variant") === variant
);
796 this.myid
= (continuation
? localStorage
.getItem("myid") : getRandString());
799 // HACK: play a small silent sound to allow "new game" sound later
800 // if tab not focused (TODO: does it really work ?!)
801 new Audio("/sounds/silent.mp3").play().then(() => {}).catch(err
=> {});
803 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
804 const socketOpenListener
= () => {
807 const fen
= localStorage
.getItem("fen");
808 const mycolor
= localStorage
.getItem("mycolor");
809 const oppid
= localStorage
.getItem("oppid");
810 const moves
= JSON
.parse(localStorage
.getItem("moves"));
811 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
812 // Send ping to server (answer pong if opponent is connected)
813 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
815 else if (localStorage
.getItem("newgame") === variant
)
817 // New game request has been cancelled on disconnect
818 this.newGame("human", undefined, undefined, undefined, undefined, "reconnect");
821 const socketMessageListener
= msg
=> {
822 const data
= JSON
.parse(msg
.data
);
826 // We opened another tab on the same game
829 alert("Already playing a game in this variant on another tab!");
831 case "newgame": //opponent found
832 // oppid: opponent socket ID
833 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
835 case "newmove": //..he played!
836 this.play(data
.move, "animate");
838 case "pong": //received if we sent a ping (game still alive on our side)
839 this.oppConnected
= true;
840 const L
= this.vr
.moves
.length
;
841 // Send our "last state" informations to opponent
842 this.conn
.send(JSON
.stringify({
845 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
849 case "lastate": //got opponent infos about last move (we might have resigned)
850 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
853 this.conn
.send(JSON
.stringify({
860 else if (data
.movesCount
< 0)
863 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
865 else if (data
.movesCount
< this.vr
.moves
.length
)
867 // We must tell last move to opponent
868 const L
= this.vr
.moves
.length
;
869 this.conn
.send(JSON
.stringify({
872 lastMove:this.vr
.moves
[L
-1],
876 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
877 this.play(data
.lastMove
, "animate");
879 case "resign": //..you won!
880 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
882 // TODO: also use (dis)connect info to count online players?
885 if (this.mode
== "human" && this.oppid
== data
.id
)
886 this.oppConnected
= (data
.code
== "connect");
890 const socketCloseListener
= () => {
891 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
892 this.conn
.addEventListener('open', socketOpenListener
);
893 this.conn
.addEventListener('message', socketMessageListener
);
894 this.conn
.addEventListener('close', socketCloseListener
);
896 this.conn
.onopen
= socketOpenListener
;
897 this.conn
.onmessage
= socketMessageListener
;
898 this.conn
.onclose
= socketCloseListener
;
899 // Listen to keyboard left/right to navigate in game
900 document
.onkeydown
= event
=> {
901 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
902 && [37,39].includes(event
.keyCode
))
904 event
.preventDefault();
905 if (event
.keyCode
== 37) //Back
913 download: function() {
914 let content
= document
.getElementById("pgn-game").innerHTML
;
915 content
= content
.replace(/<br>/g, "\n");
916 // Prepare and trigger download link
917 let downloadAnchor
= document
.getElementById("download");
918 downloadAnchor
.setAttribute("download", "game.pgn");
919 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
920 encodeURIComponent(content
);
921 downloadAnchor
.click();
923 endGame: function(score
) {
925 let modalBox
= document
.getElementById("modal-eog");
926 modalBox
.checked
= true;
927 // Variants may have special PGN structure (so next function isn't defined here)
928 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
929 setTimeout(() => { modalBox
.checked
= false; }, 2000);
930 if (this.mode
== "human")
933 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
936 getEndgameMessage: function(score
) {
937 let eogMessage
= "Unfinished";
941 eogMessage
= "White win";
944 eogMessage
= "Black win";
952 setStorage: function() {
953 localStorage
.setItem("myid", this.myid
);
954 localStorage
.setItem("variant", variant
);
955 localStorage
.setItem("mycolor", this.mycolor
);
956 localStorage
.setItem("oppid", this.oppid
);
957 localStorage
.setItem("fenStart", this.fenStart
);
958 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
959 localStorage
.setItem("fen", this.vr
.getFen());
961 updateStorage: function() {
962 localStorage
.setItem("moves", JSON
.stringify(this.vr
.moves
));
963 localStorage
.setItem("fen", this.vr
.getFen());
965 clearStorage: function() {
966 delete localStorage
["variant"];
967 delete localStorage
["myid"];
968 delete localStorage
["mycolor"];
969 delete localStorage
["oppid"];
970 delete localStorage
["fenStart"];
971 delete localStorage
["fen"];
972 delete localStorage
["moves"];
974 // HACK because mini-css tooltips are persistent after click...
975 getRidOfTooltip: function(elt
) {
976 elt
.style
.visibility
= "hidden";
977 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
979 showSettings: function(e
) {
980 this.getRidOfTooltip(e
.currentTarget
);
981 document
.getElementById("modal-settings").checked
= true;
983 toggleHints: function() {
984 this.hints
= !this.hints
;
985 setCookie("hints", this.hints
? "1" : "0");
987 setColor: function(e
) {
988 this.color
= e
.target
.options
[e
.target
.selectedIndex
].value
;
989 setCookie("color", this.color
);
991 setSound: function(e
) {
992 this.sound
= parseInt(e
.target
.options
[e
.target
.selectedIndex
].value
);
993 setCookie("sound", this.sound
);
995 clickGameSeek: function(e
) {
996 this.getRidOfTooltip(e
.currentTarget
);
997 if (this.mode
== "human")
998 return; //no newgame while playing
1001 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
1002 delete localStorage
["newgame"]; //cancel game seek
1006 this.newGame("human");
1008 clickComputerGame: function(e
) {
1009 this.getRidOfTooltip(e
.currentTarget
);
1010 if (this.mode
== "human")
1011 return; //no newgame while playing
1012 this.newGame("computer");
1014 clickFriendGame: function(e
) {
1015 this.getRidOfTooltip(e
.currentTarget
);
1016 document
.getElementById("modal-fenedit").checked
= true;
1018 resign: function(e
) {
1019 this.getRidOfTooltip(e
.currentTarget
);
1020 if (this.mode
== "human" && this.oppConnected
)
1023 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
1024 } catch (INVALID_STATE_ERR
) {
1025 return; //socket is not ready (and not yet reconnected)
1028 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
1030 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
1031 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
1032 console
.log(fen
); //DEBUG
1033 if (mode
=="human" && !oppId
)
1035 const storageVariant
= localStorage
.getItem("variant");
1036 if (!!storageVariant
&& storageVariant
!== variant
)
1037 return alert("Finish your " + storageVariant
+ " game first!");
1038 // Send game request and wait..
1039 localStorage
["newgame"] = variant
;
1041 this.clearStorage(); //in case of
1043 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
1044 } catch (INVALID_STATE_ERR
) {
1045 return; //nothing achieved
1047 if (continuation
!== "reconnect") //TODO: bad HACK...
1049 let modalBox
= document
.getElementById("modal-newgame");
1050 modalBox
.checked
= true;
1051 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1055 this.vr
= new VariantRules(fen
, moves
|| []);
1057 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
1059 this.incheck
= []; //in case of
1060 this.fenStart
= (continuation
? localStorage
.getItem("fenStart") : fen
);
1064 if (!continuation
) //not playing sound on game continuation
1066 if (this.sound
>= 1)
1067 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
1068 document
.getElementById("modal-newgame").checked
= false;
1071 this.oppConnected
= !continuation
;
1072 this.mycolor
= color
;
1074 if (!!moves
&& moves
.length
> 0) //imply continuation
1076 const lastMove
= moves
[moves
.length
-1];
1077 this.vr
.undo(lastMove
);
1078 this.incheck
= this.vr
.getCheckSquares(lastMove
);
1079 this.vr
.play(lastMove
, "ingame");
1081 delete localStorage
["newgame"];
1082 this.setStorage(); //in case of interruptions
1084 else if (mode
== "computer")
1086 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
1087 if (this.mycolor
== 'b')
1088 setTimeout(this.playComputerMove
, 500);
1090 //else: against a (IRL) friend or problem solving: nothing more to do
1092 playComputerMove: function() {
1093 const timeStart
= Date
.now();
1094 const compMove
= this.vr
.getComputerMove();
1095 // (first move) HACK: avoid selecting elements before they appear on page:
1096 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
1098 if (this.mode
== "computer") //Warning: mode could have changed!
1099 this.play(compMove
, "animate")
1102 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1103 getSquareId: function(o
) {
1104 // NOTE: a separator is required to allow any size of board
1105 return "sq-" + o
.x
+ "-" + o
.y
;
1108 getSquareFromId: function(id
) {
1109 let idParts
= id
.split('-');
1110 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
1112 mousedown: function(e
) {
1113 e
= e
|| window
.event
;
1115 let elem
= e
.target
;
1116 while (!ingame
&& elem
!== null)
1118 if (elem
.classList
.contains("game"))
1123 elem
= elem
.parentElement
;
1125 if (!ingame
) //let default behavior (click on button...)
1127 e
.preventDefault(); //disable native drag & drop
1128 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
1130 // Next few lines to center the piece on mouse cursor
1131 let rect
= e
.target
.parentNode
.getBoundingClientRect();
1133 x: rect
.x
+ rect
.width
/2,
1134 y: rect
.y
+ rect
.width
/2,
1135 id: e
.target
.parentNode
.id
1137 this.selectedPiece
= e
.target
.cloneNode();
1138 this.selectedPiece
.style
.position
= "absolute";
1139 this.selectedPiece
.style
.top
= 0;
1140 this.selectedPiece
.style
.display
= "inline-block";
1141 this.selectedPiece
.style
.zIndex
= 3000;
1142 let startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1143 const iCanPlay
= this.mode
!="idle" &&
1144 (["friend","problem"].includes(this.mode
) ||
1145 this.vr
.canIplay(this.mycolor
,startSquare
));
1146 this.possibleMoves
= iCanPlay
? this.vr
.getPossibleMovesFrom(startSquare
) : [];
1147 // Next line add moving piece just after current image
1148 // (required for Crazyhouse reserve)
1149 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1152 mousemove: function(e
) {
1153 if (!this.selectedPiece
)
1155 e
= e
|| window
.event
;
1156 // If there is an active element, move it around
1157 if (!!this.selectedPiece
)
1159 const [offsetX
,offsetY
] = !!e
.clientX
1160 ? [e
.clientX
,e
.clientY
] //desktop browser
1161 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1162 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1163 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1166 mouseup: function(e
) {
1167 if (!this.selectedPiece
)
1169 e
= e
|| window
.event
;
1170 // Read drop target (or parentElement, parentNode... if type == "img")
1171 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1172 const [offsetX
,offsetY
] = !!e
.clientX
1173 ? [e
.clientX
,e
.clientY
]
1174 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1175 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1176 this.selectedPiece
.style
.zIndex
= 3000;
1177 // Next condition: classList.contains(piece) fails because of marks
1178 while (landing
.tagName
== "IMG")
1179 landing
= landing
.parentNode
;
1180 if (this.start
.id
== landing
.id
)
1182 // A click: selectedPiece and possibleMoves are already filled
1185 // OK: process move attempt
1186 let endSquare
= this.getSquareFromId(landing
.id
);
1187 let moves
= this.findMatchingMoves(endSquare
);
1188 this.possibleMoves
= [];
1189 if (moves
.length
> 1)
1190 this.choices
= moves
;
1191 else if (moves
.length
==1)
1192 this.play(moves
[0]);
1193 // Else: impossible move
1194 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1195 delete this.selectedPiece
;
1196 this.selectedPiece
= null;
1198 findMatchingMoves: function(endSquare
) {
1199 // Run through moves list and return the matching set (if promotions...)
1201 this.possibleMoves
.forEach(function(m
) {
1202 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1207 animateMove: function(move) {
1208 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1209 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1210 let rectStart
= startSquare
.getBoundingClientRect();
1211 let rectEnd
= endSquare
.getBoundingClientRect();
1212 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1214 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1215 // HACK for animation (with positive translate, image slides "under background")
1216 // Possible improvement: just alter squares on the piece's way...
1217 squares
= document
.getElementsByClassName("board");
1218 for (let i
=0; i
<squares
.length
; i
++)
1220 let square
= squares
.item(i
);
1221 if (square
.id
!= this.getSquareId(move.start
))
1222 square
.style
.zIndex
= "-1";
1224 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1225 translation
.y
+ "px)";
1226 movingPiece
.style
.transitionDuration
= "0.2s";
1227 movingPiece
.style
.zIndex
= "3000";
1229 for (let i
=0; i
<squares
.length
; i
++)
1230 squares
.item(i
).style
.zIndex
= "auto";
1231 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1235 play: function(move, programmatic
) {
1238 // Navigate after game is over
1239 if (this.cursor
>= this.vr
.moves
.length
)
1240 return; //already at the end
1241 move = this.vr
.moves
[this.cursor
++];
1243 if (!!programmatic
) //computer or human opponent
1245 this.animateMove(move);
1248 // Not programmatic, or animation is over
1249 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1250 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1251 if (this.sound
== 2)
1252 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
1253 if (this.mode
!= "idle")
1255 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1256 this.vr
.play(move, "ingame");
1260 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1261 this.$forceUpdate(); //TODO: ?!
1263 if (this.mode
== "human")
1264 this.updateStorage(); //after our moves and opponent moves
1265 if (this.mode
!= "idle")
1267 const eog
= this.vr
.checkGameOver();
1271 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1272 setTimeout(this.playComputerMove
, 500);
1275 // Navigate after game is over
1276 if (this.cursor
== 0)
1277 return; //already at the beginning
1278 if (this.cursor
== this.vr
.moves
.length
)
1279 this.incheck
= []; //in case of...
1280 const move = this.vr
.moves
[--this.cursor
];
1281 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1282 this.$forceUpdate(); //TODO: ?!
1284 undoInGame: function() {
1285 const lm
= this.vr
.lastMove
;