9d7bb1fbf7da57e47621d5c34b55e713665648fd
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 this.newGame("problem", p
.fen
, V
.ParseFen(p
.fen
).turn
);
34 const [sizeX
,sizeY
] = [V
.size
.x
,V
.size
.y
];
35 const smallScreen
= (window
.innerWidth
<= 420);
36 // Precompute hints squares to facilitate rendering
37 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
38 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
39 // Also precompute in-check squares
40 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
41 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
42 let elementArray
= [];
47 on: { click: this.clickGameSeek
},
48 attrs: { "aria-label": 'New online game' },
51 "bottom": true, //display below
53 "playing": this.mode
== "human",
57 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
59 if (["idle","computer"].includes(this.mode
))
64 on: { click: this.clickComputerGame
},
65 attrs: { "aria-label": 'New game VS computer' },
69 "playing": this.mode
== "computer",
73 [h('i', { 'class': { "material-icons": true } }, "computer")])
76 if (["idle","friend"].includes(this.mode
))
81 on: { click: this.clickFriendGame
},
82 attrs: { "aria-label": 'New IRL game' },
86 "playing": this.mode
== "friend",
90 [h('i', { 'class': { "material-icons": true } }, "people")])
95 const square00
= document
.getElementById("sq-0-0");
96 const squareWidth
= !!square00
97 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
99 const settingsBtnElt
= document
.getElementById("settingsBtn");
100 const indicWidth
= !!settingsBtnElt
//-2 for border:
101 ? parseFloat(window
.getComputedStyle(settingsBtnElt
).height
.slice(0,-2)) - 2
102 : (smallScreen
? 31 : 37);
103 if (this.mode
== "human")
105 const connectedIndic
= h(
109 "topindicator": true,
111 "connected": this.oppConnected
,
112 "disconnected": !this.oppConnected
,
115 "width": indicWidth
+ "px",
116 "height": indicWidth
+ "px",
120 elementArray
.push(connectedIndic
);
126 "topindicator": true,
128 "white-turn": this.vr
.turn
=="w",
129 "black-turn": this.vr
.turn
=="b",
132 "width": indicWidth
+ "px",
133 "height": indicWidth
+ "px",
137 elementArray
.push(turnIndic
);
138 const settingsBtn
= h(
141 on: { click: this.showSettings
},
143 "aria-label": 'Settings',
148 "topindicator": true,
150 "settings-btn": !smallScreen
,
151 "settings-btn-small": smallScreen
,
154 [h('i', { 'class': { "material-icons": true } }, "settings")]
156 elementArray
.push(settingsBtn
);
157 if (this.mode
== "problem")
159 // Show problem instructions
163 attrs: { id: "instructions-div" },
164 "class": { "section-content": true },
169 attrs: { id: "problem-instructions" },
170 domProps: { innerHTML: this.problem
.instructions
}
177 const choices
= h('div',
179 attrs: { "id": "choices" },
180 'class': { 'row': true },
182 "display": this.choices
.length
>0?"block":"none",
183 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
184 "width": (this.choices
.length
* squareWidth
) + "px",
185 "height": squareWidth
+ "px",
188 this.choices
.map( m
=> { //a "choice" is a move
193 ['board'+sizeY
]: true,
196 'width': (100/this.choices
.length
) + "%",
197 'padding-bottom': (100/this.choices
.length
) + "%",
202 attrs: { "src": '/images/pieces/' +
203 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
204 'class': { 'choice-piece': true },
205 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
211 // Create board element (+ reserves if needed by variant or mode)
212 const lm
= this.vr
.lastMove
;
213 const showLight
= this.hints
&&
214 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
215 const gameDiv
= h('div',
217 'class': { 'game': true },
219 [_
.range(sizeX
).map(i
=> {
220 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
227 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
229 _
.range(sizeY
).map(j
=> {
230 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
232 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
240 'ghost': !!this.selectedPiece
241 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
244 src: "/images/pieces/" +
245 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
251 if (this.hints
&& hintSquares
[ci
][cj
])
261 src: "/images/mark.svg",
272 ['board'+sizeY
]: true,
273 'light-square': (i
+j
)%2==0,
274 'dark-square': (i
+j
)%2==1,
276 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
277 'incheck': showLight
&& incheckSq
[ci
][cj
],
280 id: this.getSquareId({x:ci
,y:cj
}),
289 if (this.mode
!= "idle")
294 on: { click: this.resign
},
295 attrs: { "aria-label": 'Resign' },
299 "small": smallScreen
,
302 [h('i', { 'class': { "material-icons": true } }, "flag")])
305 else if (this.vr
.moves
.length
> 0)
307 // A game finished, and another is not started yet: allow navigation
308 actionArray
= actionArray
.concat([
311 on: { click: e
=> this.undo() },
312 attrs: { "aria-label": 'Undo' },
314 "small": smallScreen
,
318 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
321 on: { click: e
=> this.play() },
322 attrs: { "aria-label": 'Play' },
323 "class": { "small": smallScreen
},
325 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
329 if (this.mode
== "friend")
331 actionArray
= actionArray
.concat(
335 on: { click: this.undoInGame
},
336 attrs: { "aria-label": 'Undo' },
338 "small": smallScreen
,
342 [h('i', { 'class': { "material-icons": true } }, "undo")]
346 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
347 attrs: { "aria-label": 'Flip' },
348 "class": { "small": smallScreen
},
350 [h('i', { 'class': { "material-icons": true } }, "cached")]
354 elementArray
.push(gameDiv
);
355 if (!!this.vr
.reserve
)
357 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
358 let myReservePiecesArray
= [];
359 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
361 myReservePiecesArray
.push(h('div',
363 'class': {'board':true, ['board'+sizeY
]:true},
364 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
369 'class': {"piece":true},
371 "src": "/images/pieces/" +
372 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
376 {"class": { "reserve-count": true } },
377 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
381 let oppReservePiecesArray
= [];
382 const oppCol
= this.vr
.getOppCol(this.mycolor
);
383 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
385 oppReservePiecesArray
.push(h('div',
387 'class': {'board':true, ['board'+sizeY
]:true},
388 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
393 'class': {"piece":true},
395 "src": "/images/pieces/" +
396 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
400 {"class": { "reserve-count": true } },
401 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
405 let reserves
= h('div',
417 "reserve-row-1": true,
423 { 'class': { 'row': true }},
424 oppReservePiecesArray
428 elementArray
.push(reserves
);
433 attrs: { "id": "modal-eog", type: "checkbox" },
434 "class": { "modal": true },
438 attrs: { "role": "dialog", "aria-labelledby": "eogMessage" },
443 "class": { "card": true, "smallpad": true },
448 attrs: { "for": "modal-eog" },
449 "class": { "modal-close": true },
454 attrs: { "id": "eogMessage" },
455 "class": { "section": true },
456 domProps: { innerHTML: this.endgameMessage
},
464 elementArray
= elementArray
.concat(modalEog
);
466 // NOTE: this modal could be in Pug view (no usage of Vue functions or variables)
467 const modalNewgame
= [
470 attrs: { "id": "modal-newgame", type: "checkbox" },
471 "class": { "modal": true },
475 attrs: { "role": "dialog", "aria-labelledby": "newGameTxt" },
480 "class": { "card": true, "smallpad": true },
485 attrs: { "id": "close-newgame", "for": "modal-newgame" },
486 "class": { "modal-close": true },
491 attrs: { "id": "newGameTxt" },
492 "class": { "section": true },
493 domProps: { innerHTML: "New game" },
498 "class": { "section": true },
499 domProps: { innerHTML: "Waiting for opponent..." },
507 elementArray
= elementArray
.concat(modalNewgame
);
508 const modalFenEdit
= [
511 attrs: { "id": "modal-fenedit", type: "checkbox" },
512 "class": { "modal": true },
516 attrs: { "role": "dialog", "aria-labelledby": "titleFenedit" },
521 "class": { "card": true, "smallpad": true },
526 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
527 "class": { "modal-close": true },
532 attrs: { "id": "titleFenedit" },
533 "class": { "section": true },
534 domProps: { innerHTML: "Position + flags (FEN):" },
542 value: VariantRules
.GenRandInitFen(),
550 const fen
= document
.getElementById("input-fen").value
;
551 document
.getElementById("modal-fenedit").checked
= false;
552 this.newGame("friend", fen
);
555 domProps: { innerHTML: "Ok" },
562 document
.getElementById("input-fen").value
=
563 VariantRules
.GenRandInitFen();
566 domProps: { innerHTML: "Random" },
574 elementArray
= elementArray
.concat(modalFenEdit
);
575 const modalSettings
= [
578 attrs: { "id": "modal-settings", type: "checkbox" },
579 "class": { "modal": true },
583 attrs: { "role": "dialog", "aria-labelledby": "settingsTitle" },
588 "class": { "card": true, "smallpad": true },
593 attrs: { "id": "close-settings", "for": "modal-settings" },
594 "class": { "modal-close": true },
599 attrs: { "id": "settingsTitle" },
600 "class": { "section": true },
601 domProps: { innerHTML: "Preferences" },
607 //h('legend', { domProps: { innerHTML: "Legend title" } }),
610 attrs: { for: "setHints" },
611 domProps: { innerHTML: "Show hints?" },
621 on: { "change": this.toggleHints
},
631 attrs: { for: "selectColor" },
632 domProps: { innerHTML: "Board colors" },
637 attrs: { "id": "selectColor" },
638 on: { "change": this.setColor
},
647 attrs: { "selected": this.color
=="lichess" },
656 attrs: { "selected": this.color
=="chesscom" },
662 "value": "chesstempo",
665 attrs: { "selected": this.color
=="chesstempo" },
677 attrs: { for: "selectSound" },
678 domProps: { innerHTML: "Play sounds?" },
683 attrs: { "id": "selectSound" },
684 on: { "change": this.setSound
},
693 attrs: { "selected": this.sound
==0 },
702 attrs: { "selected": this.sound
==1 },
711 attrs: { "selected": this.sound
==2 },
723 elementArray
= elementArray
.concat(modalSettings
);
724 const actions
= h('div',
726 attrs: { "id": "actions" },
727 'class': { 'text-center': true },
731 elementArray
.push(actions
);
732 if (this.score
!= "*" && this.pgnTxt
.length
> 0)
737 attrs: { id: "pgn-div" },
738 "class": { "section-content": true },
751 attrs: { id: "pgn-game" },
752 domProps: { innerHTML: this.pgnTxt
}
757 attrs: { "id": "downloadBtn" },
758 on: { click: this.download
},
759 domProps: { innerHTML: "Download game" },
766 else if (this.mode
!= "idle")
768 if (this.mode
== "problem")
770 // Show problem solution (on click)
774 attrs: { id: "solution-div" },
775 "class": { "section-content": true },
780 domProps: { innerHTML: "Show solution" },
781 on: { click: "toggleShowSolution" }
786 attrs: { id: "problem-solution" },
787 domProps: { innerHTML: this.problem
.solution
}
798 attrs: { id: "fen-div" },
799 "class": { "section-content": true },
804 attrs: { id: "fen-string" },
805 domProps: { innerHTML: this.vr
.getBaseFen() }
818 "col-md-offset-2":true,
820 "col-lg-offset-3":true,
822 // NOTE: click = mousedown + mouseup
824 mousedown: this.mousedown
,
825 mousemove: this.mousemove
,
826 mouseup: this.mouseup
,
827 touchstart: this.mousedown
,
828 touchmove: this.mousemove
,
829 touchend: this.mouseup
,
836 endgameMessage: function() {
837 let eogMessage
= "Unfinished";
841 eogMessage
= "White win";
844 eogMessage
= "Black win";
853 created: function() {
854 const url
= socketUrl
;
855 const humanContinuation
= (localStorage
.getItem("variant") === variant
);
856 const computerContinuation
= (localStorage
.getItem("comp-variant") === variant
);
857 this.myid
= (humanContinuation
? localStorage
.getItem("myid") : getRandString());
858 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
859 const socketOpenListener
= () => {
860 if (humanContinuation
) //game VS human has priority
862 const fen
= localStorage
.getItem("fen");
863 const mycolor
= localStorage
.getItem("mycolor");
864 const oppid
= localStorage
.getItem("oppid");
865 const moves
= JSON
.parse(localStorage
.getItem("moves"));
866 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
867 // Send ping to server (answer pong if opponent is connected)
868 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
870 else if (computerContinuation
)
872 const fen
= localStorage
.getItem("comp-fen");
873 const mycolor
= localStorage
.getItem("comp-mycolor");
874 const moves
= JSON
.parse(localStorage
.getItem("comp-moves"));
875 this.newGame("computer", fen
, mycolor
, undefined, moves
, true);
878 const socketMessageListener
= msg
=> {
879 const data
= JSON
.parse(msg
.data
);
883 // We opened another tab on the same game
886 alert("Already playing a game in this variant on another tab!");
888 case "newgame": //opponent found
889 // oppid: opponent socket ID
890 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
892 case "newmove": //..he played!
893 this.play(data
.move, "animate");
895 case "pong": //received if we sent a ping (game still alive on our side)
896 this.oppConnected
= true;
897 const L
= this.vr
.moves
.length
;
898 // Send our "last state" informations to opponent
899 this.conn
.send(JSON
.stringify({
902 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
906 case "lastate": //got opponent infos about last move (we might have resigned)
907 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
910 this.conn
.send(JSON
.stringify({
917 else if (data
.movesCount
< 0)
920 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
922 else if (data
.movesCount
< this.vr
.moves
.length
)
924 // We must tell last move to opponent
925 const L
= this.vr
.moves
.length
;
926 this.conn
.send(JSON
.stringify({
929 lastMove:this.vr
.moves
[L
-1],
933 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
934 this.play(data
.lastMove
, "animate");
936 case "resign": //..you won!
937 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
939 // TODO: also use (dis)connect info to count online players?
942 if (this.mode
== "human" && this.oppid
== data
.id
)
943 this.oppConnected
= (data
.code
== "connect");
947 const socketCloseListener
= () => {
948 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
949 this.conn
.addEventListener('open', socketOpenListener
);
950 this.conn
.addEventListener('message', socketMessageListener
);
951 this.conn
.addEventListener('close', socketCloseListener
);
953 this.conn
.onopen
= socketOpenListener
;
954 this.conn
.onmessage
= socketMessageListener
;
955 this.conn
.onclose
= socketCloseListener
;
956 // Listen to keyboard left/right to navigate in game
957 document
.onkeydown
= event
=> {
958 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
959 && [37,39].includes(event
.keyCode
))
961 event
.preventDefault();
962 if (event
.keyCode
== 37) //Back
970 toggleShowSolution: function() {
971 let problemSolution
= document
.getElementById("problem-solution");
972 problemSolution
.style
.display
= problemSolution
.style
.display
== "none"
976 download: function() {
977 let content
= document
.getElementById("pgn-game").innerHTML
;
978 content
= content
.replace(/<br>/g, "\n");
979 // Prepare and trigger download link
980 let downloadAnchor
= document
.getElementById("download");
981 downloadAnchor
.setAttribute("download", "game.pgn");
982 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
983 encodeURIComponent(content
);
984 downloadAnchor
.click();
986 showScoreMsg: function() {
987 let modalBox
= document
.getElementById("modal-eog");
988 modalBox
.checked
= true;
989 setTimeout(() => { modalBox
.checked
= false; }, 2000);
991 endGame: function(score
) {
994 // Variants may have special PGN structure (so next function isn't defined here)
995 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
996 if (["human","computer"].includes(this.mode
))
999 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
1002 setStorage: function() {
1003 if (this.mode
=="human")
1005 localStorage
.setItem("myid", this.myid
);
1006 localStorage
.setItem("oppid", this.oppid
);
1008 // 'prefix' = "comp-" to resume games vs. computer
1009 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1010 localStorage
.setItem(prefix
+"variant", variant
);
1011 localStorage
.setItem(prefix
+"mycolor", this.mycolor
);
1012 localStorage
.setItem(prefix
+"fenStart", this.fenStart
);
1013 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1014 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1016 updateStorage: function() {
1017 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1018 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1019 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1021 clearStorage: function() {
1022 if (this.mode
=="human")
1024 delete localStorage
["myid"];
1025 delete localStorage
["oppid"];
1027 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1028 delete localStorage
[prefix
+"variant"];
1029 delete localStorage
[prefix
+"mycolor"];
1030 delete localStorage
[prefix
+"fenStart"];
1031 delete localStorage
[prefix
+"fen"];
1032 delete localStorage
[prefix
+"moves"];
1034 // HACK because mini-css tooltips are persistent after click...
1035 getRidOfTooltip: function(elt
) {
1036 elt
.style
.visibility
= "hidden";
1037 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
1039 showSettings: function(e
) {
1040 this.getRidOfTooltip(e
.currentTarget
);
1041 document
.getElementById("modal-settings").checked
= true;
1043 toggleHints: function() {
1044 this.hints
= !this.hints
;
1045 setCookie("hints", this.hints
? "1" : "0");
1047 setColor: function(e
) {
1048 this.color
= e
.target
.options
[e
.target
.selectedIndex
].value
;
1049 setCookie("color", this.color
);
1051 setSound: function(e
) {
1052 this.sound
= parseInt(e
.target
.options
[e
.target
.selectedIndex
].value
);
1053 setCookie("sound", this.sound
);
1055 clickGameSeek: function(e
) {
1056 this.getRidOfTooltip(e
.currentTarget
);
1057 if (this.mode
== "human")
1058 return; //no newgame while playing
1061 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
1065 this.newGame("human");
1067 clickComputerGame: function(e
) {
1068 this.getRidOfTooltip(e
.currentTarget
);
1069 if (this.mode
== "human")
1070 return; //no newgame while playing
1071 this.newGame("computer");
1073 clickFriendGame: function(e
) {
1074 this.getRidOfTooltip(e
.currentTarget
);
1075 document
.getElementById("modal-fenedit").checked
= true;
1077 resign: function(e
) {
1078 this.getRidOfTooltip(e
.currentTarget
);
1079 if (this.mode
== "human" && this.oppConnected
)
1082 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
1083 } catch (INVALID_STATE_ERR
) {
1084 return; //socket is not ready (and not yet reconnected)
1087 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
1089 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
1090 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
1091 console
.log(fen
); //DEBUG
1092 if (mode
=="human" && !oppId
)
1094 const storageVariant
= localStorage
.getItem("variant");
1095 if (!!storageVariant
&& storageVariant
!== variant
)
1096 return alert("Finish your " + storageVariant
+ " game first!");
1097 // Send game request and wait..
1099 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
1100 } catch (INVALID_STATE_ERR
) {
1101 return; //nothing achieved
1104 let modalBox
= document
.getElementById("modal-newgame");
1105 modalBox
.checked
= true;
1106 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1109 if (mode
== "computer" && !continuation
)
1111 const storageVariant
= localStorage
.getItem("comp-variant");
1112 if (!!storageVariant
&& storageVariant
!== variant
)
1114 if (!confirm("Unfinished " + storageVariant
+
1115 " computer game will be erased"))
1121 if (this.mode
== "computer" && mode
== "human")
1123 // Save current computer game to resume it later
1126 this.vr
= new VariantRules(fen
, moves
|| []);
1128 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
1130 if (continuation
&& moves
.length
> 0) //NOTE: "continuation": redundant test
1132 const lastMove
= moves
[moves
.length
-1];
1133 this.vr
.undo(lastMove
);
1134 this.incheck
= this.vr
.getCheckSquares(lastMove
);
1135 this.vr
.play(lastMove
, "ingame");
1141 const prefix
= (mode
=="computer" ? "comp-" : "");
1142 this.fenStart
= localStorage
.getItem(prefix
+"fenStart");
1145 this.fenStart
= fen
;
1149 if (!continuation
) //not playing sound on game continuation
1151 if (this.sound
>= 1)
1152 new Audio("/sounds/newgame.mp3").play().catch(err
=> {});
1153 document
.getElementById("modal-newgame").checked
= false;
1156 this.oppConnected
= !continuation
;
1157 this.mycolor
= color
;
1159 this.setStorage(); //in case of interruptions
1161 else if (mode
== "computer")
1163 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
1164 if (this.mycolor
== 'b')
1165 this.playComputerMove();
1167 //else: against a (IRL) friend or problem solving: nothing more to do
1169 playComputerMove: function() {
1170 const timeStart
= Date
.now();
1171 const compMove
= this.vr
.getComputerMove();
1172 // (first move) HACK: avoid selecting elements before they appear on page:
1173 const delay
= Math
.max(500-(Date
.now()-timeStart
), 0);
1175 if (this.mode
== "computer") //Warning: mode could have changed!
1176 this.play(compMove
, "animate")
1179 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1180 getSquareId: function(o
) {
1181 // NOTE: a separator is required to allow any size of board
1182 return "sq-" + o
.x
+ "-" + o
.y
;
1185 getSquareFromId: function(id
) {
1186 let idParts
= id
.split('-');
1187 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
1189 mousedown: function(e
) {
1190 e
= e
|| window
.event
;
1192 let elem
= e
.target
;
1193 while (!ingame
&& elem
!== null)
1195 if (elem
.classList
.contains("game"))
1200 elem
= elem
.parentElement
;
1202 if (!ingame
) //let default behavior (click on button...)
1204 e
.preventDefault(); //disable native drag & drop
1205 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
1207 // Next few lines to center the piece on mouse cursor
1208 let rect
= e
.target
.parentNode
.getBoundingClientRect();
1210 x: rect
.x
+ rect
.width
/2,
1211 y: rect
.y
+ rect
.width
/2,
1212 id: e
.target
.parentNode
.id
1214 this.selectedPiece
= e
.target
.cloneNode();
1215 this.selectedPiece
.style
.position
= "absolute";
1216 this.selectedPiece
.style
.top
= 0;
1217 this.selectedPiece
.style
.display
= "inline-block";
1218 this.selectedPiece
.style
.zIndex
= 3000;
1219 const startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1220 this.possibleMoves
= [];
1221 if (this.mode
!= "idle")
1223 const color
= ["friend","problem"].includes(this.mode
)
1226 if (this.vr
.canIplay(color
,startSquare
))
1227 this.possibleMoves
= this.vr
.getPossibleMovesFrom(startSquare
);
1229 // Next line add moving piece just after current image
1230 // (required for Crazyhouse reserve)
1231 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1234 mousemove: function(e
) {
1235 if (!this.selectedPiece
)
1237 e
= e
|| window
.event
;
1238 // If there is an active element, move it around
1239 if (!!this.selectedPiece
)
1241 const [offsetX
,offsetY
] = !!e
.clientX
1242 ? [e
.clientX
,e
.clientY
] //desktop browser
1243 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1244 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1245 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1248 mouseup: function(e
) {
1249 if (!this.selectedPiece
)
1251 e
= e
|| window
.event
;
1252 // Read drop target (or parentElement, parentNode... if type == "img")
1253 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1254 const [offsetX
,offsetY
] = !!e
.clientX
1255 ? [e
.clientX
,e
.clientY
]
1256 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1257 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1258 this.selectedPiece
.style
.zIndex
= 3000;
1259 // Next condition: classList.contains(piece) fails because of marks
1260 while (landing
.tagName
== "IMG")
1261 landing
= landing
.parentNode
;
1262 if (this.start
.id
== landing
.id
)
1264 // A click: selectedPiece and possibleMoves are already filled
1267 // OK: process move attempt
1268 let endSquare
= this.getSquareFromId(landing
.id
);
1269 let moves
= this.findMatchingMoves(endSquare
);
1270 this.possibleMoves
= [];
1271 if (moves
.length
> 1)
1272 this.choices
= moves
;
1273 else if (moves
.length
==1)
1274 this.play(moves
[0]);
1275 // Else: impossible move
1276 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1277 delete this.selectedPiece
;
1278 this.selectedPiece
= null;
1280 findMatchingMoves: function(endSquare
) {
1281 // Run through moves list and return the matching set (if promotions...)
1283 this.possibleMoves
.forEach(function(m
) {
1284 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1289 animateMove: function(move) {
1290 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1291 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1292 let rectStart
= startSquare
.getBoundingClientRect();
1293 let rectEnd
= endSquare
.getBoundingClientRect();
1294 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1296 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1297 // HACK for animation (with positive translate, image slides "under background")
1298 // Possible improvement: just alter squares on the piece's way...
1299 squares
= document
.getElementsByClassName("board");
1300 for (let i
=0; i
<squares
.length
; i
++)
1302 let square
= squares
.item(i
);
1303 if (square
.id
!= this.getSquareId(move.start
))
1304 square
.style
.zIndex
= "-1";
1306 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1307 translation
.y
+ "px)";
1308 movingPiece
.style
.transitionDuration
= "0.2s";
1309 movingPiece
.style
.zIndex
= "3000";
1311 for (let i
=0; i
<squares
.length
; i
++)
1312 squares
.item(i
).style
.zIndex
= "auto";
1313 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1317 play: function(move, programmatic
) {
1320 // Navigate after game is over
1321 if (this.cursor
>= this.vr
.moves
.length
)
1322 return; //already at the end
1323 move = this.vr
.moves
[this.cursor
++];
1325 if (!!programmatic
) //computer or human opponent
1327 this.animateMove(move);
1330 // Not programmatic, or animation is over
1331 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1332 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1333 if (this.sound
== 2)
1334 new Audio("/sounds/chessmove1.mp3").play().catch(err
=> {});
1335 if (this.mode
!= "idle")
1337 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1338 this.vr
.play(move, "ingame");
1342 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1343 this.$forceUpdate(); //TODO: ?!
1345 if (["human","computer"].includes(this.mode
))
1346 this.updateStorage(); //after our moves and opponent moves
1347 if (this.mode
!= "idle")
1349 const eog
= this.vr
.checkGameOver();
1352 if (["human","computer"].includes(this.mode
))
1356 // Just show score on screen (allow undo)
1358 this.showScoreMsg();
1362 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1363 this.playComputerMove
;
1366 // Navigate after game is over
1367 if (this.cursor
== 0)
1368 return; //already at the beginning
1369 if (this.cursor
== this.vr
.moves
.length
)
1370 this.incheck
= []; //in case of...
1371 const move = this.vr
.moves
[--this.cursor
];
1372 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1373 this.$forceUpdate(); //TODO: ?!
1375 undoInGame: function() {
1376 const lm
= this.vr
.lastMove
;