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 humanContinuation
= (localStorage
.getItem("variant") === variant
);
796 const computerContinuation
= (localStorage
.getItem("comp-variant") === variant
);
797 this.myid
= (humanContinuation
? localStorage
.getItem("myid") : getRandString());
798 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
799 const socketOpenListener
= () => {
800 if (humanContinuation
) //game VS human has priority
802 const fen
= localStorage
.getItem("fen");
803 const mycolor
= localStorage
.getItem("mycolor");
804 const oppid
= localStorage
.getItem("oppid");
805 const moves
= JSON
.parse(localStorage
.getItem("moves"));
806 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
807 // Send ping to server (answer pong if opponent is connected)
808 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
810 else if (computerContinuation
)
812 const fen
= localStorage
.getItem("comp-fen");
813 const mycolor
= localStorage
.getItem("comp-mycolor");
814 const moves
= JSON
.parse(localStorage
.getItem("comp-moves"));
815 this.newGame("computer", fen
, mycolor
, undefined, moves
, true);
818 const socketMessageListener
= msg
=> {
819 const data
= JSON
.parse(msg
.data
);
823 // We opened another tab on the same game
826 alert("Already playing a game in this variant on another tab!");
828 case "newgame": //opponent found
829 // oppid: opponent socket ID
830 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
832 case "newmove": //..he played!
833 this.play(data
.move, "animate");
835 case "pong": //received if we sent a ping (game still alive on our side)
836 this.oppConnected
= true;
837 const L
= this.vr
.moves
.length
;
838 // Send our "last state" informations to opponent
839 this.conn
.send(JSON
.stringify({
842 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
846 case "lastate": //got opponent infos about last move (we might have resigned)
847 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
850 this.conn
.send(JSON
.stringify({
857 else if (data
.movesCount
< 0)
860 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
862 else if (data
.movesCount
< this.vr
.moves
.length
)
864 // We must tell last move to opponent
865 const L
= this.vr
.moves
.length
;
866 this.conn
.send(JSON
.stringify({
869 lastMove:this.vr
.moves
[L
-1],
873 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
874 this.play(data
.lastMove
, "animate");
876 case "resign": //..you won!
877 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
879 // TODO: also use (dis)connect info to count online players?
882 if (this.mode
== "human" && this.oppid
== data
.id
)
883 this.oppConnected
= (data
.code
== "connect");
887 const socketCloseListener
= () => {
888 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
889 this.conn
.addEventListener('open', socketOpenListener
);
890 this.conn
.addEventListener('message', socketMessageListener
);
891 this.conn
.addEventListener('close', socketCloseListener
);
893 this.conn
.onopen
= socketOpenListener
;
894 this.conn
.onmessage
= socketMessageListener
;
895 this.conn
.onclose
= socketCloseListener
;
896 // Listen to keyboard left/right to navigate in game
897 document
.onkeydown
= event
=> {
898 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
899 && [37,39].includes(event
.keyCode
))
901 event
.preventDefault();
902 if (event
.keyCode
== 37) //Back
910 download: function() {
911 let content
= document
.getElementById("pgn-game").innerHTML
;
912 content
= content
.replace(/<br>/g, "\n");
913 // Prepare and trigger download link
914 let downloadAnchor
= document
.getElementById("download");
915 downloadAnchor
.setAttribute("download", "game.pgn");
916 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
917 encodeURIComponent(content
);
918 downloadAnchor
.click();
920 endGame: function(score
) {
922 let modalBox
= document
.getElementById("modal-eog");
923 modalBox
.checked
= true;
924 // Variants may have special PGN structure (so next function isn't defined here)
925 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
926 setTimeout(() => { modalBox
.checked
= false; }, 2000);
927 if (["human","computer"].includes(this.mode
))
930 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
933 getEndgameMessage: function(score
) {
934 let eogMessage
= "Unfinished";
938 eogMessage
= "White win";
941 eogMessage
= "Black win";
949 setStorage: function() {
950 if (this.mode
=="human")
952 localStorage
.setItem("myid", this.myid
);
953 localStorage
.setItem("oppid", this.oppid
);
955 // 'prefix' = "comp-" to resume games vs. computer
956 const prefix
= (this.mode
=="computer" ? "comp-" : "");
957 localStorage
.setItem(prefix
+"variant", variant
);
958 localStorage
.setItem(prefix
+"mycolor", this.mycolor
);
959 localStorage
.setItem(prefix
+"fenStart", this.fenStart
);
960 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
961 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
963 updateStorage: function() {
964 const prefix
= (this.mode
=="computer" ? "comp-" : "");
965 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
966 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
968 clearStorage: function() {
969 if (this.mode
=="human")
971 delete localStorage
["myid"];
972 delete localStorage
["oppid"];
974 const prefix
= (this.mode
=="computer" ? "comp-" : "");
975 delete localStorage
[prefix
+"variant"];
976 delete localStorage
[prefix
+"mycolor"];
977 delete localStorage
[prefix
+"fenStart"];
978 delete localStorage
[prefix
+"fen"];
979 delete localStorage
[prefix
+"moves"];
981 // HACK because mini-css tooltips are persistent after click...
982 getRidOfTooltip: function(elt
) {
983 elt
.style
.visibility
= "hidden";
984 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
986 showSettings: function(e
) {
987 this.getRidOfTooltip(e
.currentTarget
);
988 document
.getElementById("modal-settings").checked
= true;
990 toggleHints: function() {
991 this.hints
= !this.hints
;
992 setCookie("hints", this.hints
? "1" : "0");
994 setColor: function(e
) {
995 this.color
= e
.target
.options
[e
.target
.selectedIndex
].value
;
996 setCookie("color", this.color
);
998 setSound: function(e
) {
999 this.sound
= parseInt(e
.target
.options
[e
.target
.selectedIndex
].value
);
1000 setCookie("sound", this.sound
);
1002 clickGameSeek: function(e
) {
1003 this.getRidOfTooltip(e
.currentTarget
);
1004 if (this.mode
== "human")
1005 return; //no newgame while playing
1008 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
1012 this.newGame("human");
1014 clickComputerGame: function(e
) {
1015 this.getRidOfTooltip(e
.currentTarget
);
1016 if (this.mode
== "human")
1017 return; //no newgame while playing
1018 this.newGame("computer");
1020 clickFriendGame: function(e
) {
1021 this.getRidOfTooltip(e
.currentTarget
);
1022 document
.getElementById("modal-fenedit").checked
= true;
1024 resign: function(e
) {
1025 this.getRidOfTooltip(e
.currentTarget
);
1026 if (this.mode
== "human" && this.oppConnected
)
1029 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
1030 } catch (INVALID_STATE_ERR
) {
1031 return; //socket is not ready (and not yet reconnected)
1034 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
1036 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
1037 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
1038 console
.log(fen
); //DEBUG
1039 if (mode
=="human" && !oppId
)
1041 const storageVariant
= localStorage
.getItem("variant");
1042 if (!!storageVariant
&& storageVariant
!== variant
)
1043 return alert("Finish your " + storageVariant
+ " game first!");
1044 // Send game request and wait..
1047 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
1048 } catch (INVALID_STATE_ERR
) {
1049 return; //nothing achieved
1051 let modalBox
= document
.getElementById("modal-newgame");
1052 modalBox
.checked
= true;
1053 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1056 if (this.mode
== "computer" && mode
== "human") { }
1058 // Save current computer game to resume it later
1061 this.vr
= new VariantRules(fen
, moves
|| []);
1063 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
1065 this.incheck
= continuation
1068 this.fenStart
= (continuation
? localStorage
.getItem("fenStart") : fen
);
1074 //TODO: refactor this. (for computer mode too), lastMove getCheckSquares...
1080 if (!continuation
) //not playing sound on game continuation
1082 if (this.sound
>= 1)
1083 new Audio("/sounds/newgame.mp3").play().then(() => {}).catch(err
=> {});
1084 document
.getElementById("modal-newgame").checked
= false;
1087 this.oppConnected
= !continuation
;
1088 this.mycolor
= color
;
1090 if (!!moves
&& moves
.length
> 0) //imply continuation
1092 const lastMove
= moves
[moves
.length
-1];
1093 this.vr
.undo(lastMove
);
1094 this.incheck
= this.vr
.getCheckSquares(lastMove
);
1095 this.vr
.play(lastMove
, "ingame");
1097 this.setStorage(); //in case of interruptions
1099 else if (mode
== "computer")
1101 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
1102 if (this.mycolor
== 'b')
1103 setTimeout(this.playComputerMove
, 500);
1105 //else: against a (IRL) friend or problem solving: nothing more to do
1107 playComputerMove: function() {
1108 const timeStart
= Date
.now();
1109 const compMove
= this.vr
.getComputerMove();
1110 // (first move) HACK: avoid selecting elements before they appear on page:
1111 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
1113 if (this.mode
== "computer") //Warning: mode could have changed!
1114 this.play(compMove
, "animate")
1117 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1118 getSquareId: function(o
) {
1119 // NOTE: a separator is required to allow any size of board
1120 return "sq-" + o
.x
+ "-" + o
.y
;
1123 getSquareFromId: function(id
) {
1124 let idParts
= id
.split('-');
1125 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
1127 mousedown: function(e
) {
1128 e
= e
|| window
.event
;
1130 let elem
= e
.target
;
1131 while (!ingame
&& elem
!== null)
1133 if (elem
.classList
.contains("game"))
1138 elem
= elem
.parentElement
;
1140 if (!ingame
) //let default behavior (click on button...)
1142 e
.preventDefault(); //disable native drag & drop
1143 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
1145 // Next few lines to center the piece on mouse cursor
1146 let rect
= e
.target
.parentNode
.getBoundingClientRect();
1148 x: rect
.x
+ rect
.width
/2,
1149 y: rect
.y
+ rect
.width
/2,
1150 id: e
.target
.parentNode
.id
1152 this.selectedPiece
= e
.target
.cloneNode();
1153 this.selectedPiece
.style
.position
= "absolute";
1154 this.selectedPiece
.style
.top
= 0;
1155 this.selectedPiece
.style
.display
= "inline-block";
1156 this.selectedPiece
.style
.zIndex
= 3000;
1157 const startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1158 this.possibleMoves
= [];
1159 if (this.mode
!= "idle")
1161 const color
= ["friend","problem"].includes(this.mode
)
1164 if (this.vr
.canIplay(color
,startSquare
))
1165 this.possibleMoves
= this.vr
.getPossibleMovesFrom(startSquare
);
1167 // Next line add moving piece just after current image
1168 // (required for Crazyhouse reserve)
1169 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1172 mousemove: function(e
) {
1173 if (!this.selectedPiece
)
1175 e
= e
|| window
.event
;
1176 // If there is an active element, move it around
1177 if (!!this.selectedPiece
)
1179 const [offsetX
,offsetY
] = !!e
.clientX
1180 ? [e
.clientX
,e
.clientY
] //desktop browser
1181 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1182 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1183 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1186 mouseup: function(e
) {
1187 if (!this.selectedPiece
)
1189 e
= e
|| window
.event
;
1190 // Read drop target (or parentElement, parentNode... if type == "img")
1191 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1192 const [offsetX
,offsetY
] = !!e
.clientX
1193 ? [e
.clientX
,e
.clientY
]
1194 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1195 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1196 this.selectedPiece
.style
.zIndex
= 3000;
1197 // Next condition: classList.contains(piece) fails because of marks
1198 while (landing
.tagName
== "IMG")
1199 landing
= landing
.parentNode
;
1200 if (this.start
.id
== landing
.id
)
1202 // A click: selectedPiece and possibleMoves are already filled
1205 // OK: process move attempt
1206 let endSquare
= this.getSquareFromId(landing
.id
);
1207 let moves
= this.findMatchingMoves(endSquare
);
1208 this.possibleMoves
= [];
1209 if (moves
.length
> 1)
1210 this.choices
= moves
;
1211 else if (moves
.length
==1)
1212 this.play(moves
[0]);
1213 // Else: impossible move
1214 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1215 delete this.selectedPiece
;
1216 this.selectedPiece
= null;
1218 findMatchingMoves: function(endSquare
) {
1219 // Run through moves list and return the matching set (if promotions...)
1221 this.possibleMoves
.forEach(function(m
) {
1222 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1227 animateMove: function(move) {
1228 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1229 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1230 let rectStart
= startSquare
.getBoundingClientRect();
1231 let rectEnd
= endSquare
.getBoundingClientRect();
1232 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1234 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1235 // HACK for animation (with positive translate, image slides "under background")
1236 // Possible improvement: just alter squares on the piece's way...
1237 squares
= document
.getElementsByClassName("board");
1238 for (let i
=0; i
<squares
.length
; i
++)
1240 let square
= squares
.item(i
);
1241 if (square
.id
!= this.getSquareId(move.start
))
1242 square
.style
.zIndex
= "-1";
1244 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1245 translation
.y
+ "px)";
1246 movingPiece
.style
.transitionDuration
= "0.2s";
1247 movingPiece
.style
.zIndex
= "3000";
1249 for (let i
=0; i
<squares
.length
; i
++)
1250 squares
.item(i
).style
.zIndex
= "auto";
1251 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1255 play: function(move, programmatic
) {
1258 // Navigate after game is over
1259 if (this.cursor
>= this.vr
.moves
.length
)
1260 return; //already at the end
1261 move = this.vr
.moves
[this.cursor
++];
1263 if (!!programmatic
) //computer or human opponent
1265 this.animateMove(move);
1268 // Not programmatic, or animation is over
1269 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1270 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1271 if (this.sound
== 2)
1272 new Audio("/sounds/chessmove1.mp3").play().then(() => {}).catch(err
=> {});
1273 if (this.mode
!= "idle")
1275 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1276 this.vr
.play(move, "ingame");
1280 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1281 this.$forceUpdate(); //TODO: ?!
1283 if (["human","computer"].includes(this.mode
))
1284 this.updateStorage(); //after our moves and opponent moves
1285 if (this.mode
!= "idle")
1287 const eog
= this.vr
.checkGameOver();
1291 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1292 setTimeout(this.playComputerMove
, 500);
1295 // Navigate after game is over
1296 if (this.cursor
== 0)
1297 return; //already at the beginning
1298 if (this.cursor
== this.vr
.moves
.length
)
1299 this.incheck
= []; //in case of...
1300 const move = this.vr
.moves
[--this.cursor
];
1301 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1302 this.$forceUpdate(); //TODO: ?!
1304 undoInGame: function() {
1305 const lm
= this.vr
.lastMove
;