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")),
25 // Web worker to play computer moves without freezing interface:
26 compWorker: new Worker('/javascripts/playCompMove.js'),
27 timeStart: undefined, //time when computer starts thinking
31 problem: function(p
, pp
) {
32 // 'problem' prop changed: update board state
33 this.newGame("problem", p
.fen
, V
.ParseFen(p
.fen
).turn
);
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 const 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
);
141 const settingsBtn
= h(
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 if (this.mode
== "problem")
162 // Show problem instructions
166 attrs: { id: "instructions-div" },
167 "class": { "section-content": true },
172 attrs: { id: "problem-instructions" },
173 domProps: { innerHTML: this.problem
.instructions
}
180 const choices
= h('div',
182 attrs: { "id": "choices" },
183 'class': { 'row': true },
185 "display": this.choices
.length
>0?"block":"none",
186 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
187 "width": (this.choices
.length
* squareWidth
) + "px",
188 "height": squareWidth
+ "px",
191 this.choices
.map( m
=> { //a "choice" is a move
196 ['board'+sizeY
]: true,
199 'width': (100/this.choices
.length
) + "%",
200 'padding-bottom': (100/this.choices
.length
) + "%",
205 attrs: { "src": '/images/pieces/' +
206 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
207 'class': { 'choice-piece': true },
208 on: { "click": e
=> { this.play(m
); this.choices
=[]; } },
214 // Create board element (+ reserves if needed by variant or mode)
215 const lm
= this.vr
.lastMove
;
216 const showLight
= this.hints
&&
217 (this.mode
!="idle" || this.cursor
==this.vr
.moves
.length
);
218 const gameDiv
= h('div',
220 'class': { 'game': true },
222 [_
.range(sizeX
).map(i
=> {
223 let ci
= this.mycolor
=='w' ? i : sizeX
-i
-1;
230 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
232 _
.range(sizeY
).map(j
=> {
233 let cj
= this.mycolor
=='w' ? j : sizeY
-j
-1;
235 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
243 'ghost': !!this.selectedPiece
244 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
247 src: "/images/pieces/" +
248 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
254 if (this.hints
&& hintSquares
[ci
][cj
])
264 src: "/images/mark.svg",
275 ['board'+sizeY
]: true,
276 'light-square': (i
+j
)%2==0,
277 'dark-square': (i
+j
)%2==1,
279 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
280 'incheck': showLight
&& incheckSq
[ci
][cj
],
283 id: this.getSquareId({x:ci
,y:cj
}),
292 if (this.mode
!= "idle")
297 on: { click: this.resign
},
298 attrs: { "aria-label": 'Resign' },
302 "small": smallScreen
,
305 [h('i', { 'class': { "material-icons": true } }, "flag")])
308 else if (this.vr
.moves
.length
> 0)
310 // A game finished, and another is not started yet: allow navigation
311 actionArray
= actionArray
.concat([
314 on: { click: e
=> this.undo() },
315 attrs: { "aria-label": 'Undo' },
317 "small": smallScreen
,
321 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
324 on: { click: e
=> this.play() },
325 attrs: { "aria-label": 'Play' },
326 "class": { "small": smallScreen
},
328 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
332 if (["friend","problem"].includes(this.mode
))
334 actionArray
= actionArray
.concat(
338 on: { click: this.undoInGame
},
339 attrs: { "aria-label": 'Undo' },
341 "small": smallScreen
,
345 [h('i', { 'class': { "material-icons": true } }, "undo")]
349 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
350 attrs: { "aria-label": 'Flip' },
351 "class": { "small": smallScreen
},
353 [h('i', { 'class': { "material-icons": true } }, "cached")]
357 elementArray
.push(gameDiv
);
358 if (!!this.vr
.reserve
)
360 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
361 let myReservePiecesArray
= [];
362 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
364 myReservePiecesArray
.push(h('div',
366 'class': {'board':true, ['board'+sizeY
]:true},
367 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
372 'class': {"piece":true},
374 "src": "/images/pieces/" +
375 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
379 {"class": { "reserve-count": true } },
380 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
384 let oppReservePiecesArray
= [];
385 const oppCol
= this.vr
.getOppCol(this.mycolor
);
386 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
388 oppReservePiecesArray
.push(h('div',
390 'class': {'board':true, ['board'+sizeY
]:true},
391 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
396 'class': {"piece":true},
398 "src": "/images/pieces/" +
399 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
403 {"class": { "reserve-count": true } },
404 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
408 let reserves
= h('div',
420 "reserve-row-1": true,
426 { 'class': { 'row': true }},
427 oppReservePiecesArray
431 elementArray
.push(reserves
);
436 attrs: { "id": "modal-eog", type: "checkbox" },
437 "class": { "modal": true },
441 attrs: { "role": "dialog", "aria-labelledby": "eogMessage" },
446 "class": { "card": true, "smallpad": true },
451 attrs: { "for": "modal-eog" },
452 "class": { "modal-close": true },
457 attrs: { "id": "eogMessage" },
458 "class": { "section": true },
459 domProps: { innerHTML: this.endgameMessage
},
467 elementArray
= elementArray
.concat(modalEog
);
469 // NOTE: this modal could be in Pug view (no usage of Vue functions or variables)
470 const modalNewgame
= [
473 attrs: { "id": "modal-newgame", type: "checkbox" },
474 "class": { "modal": true },
478 attrs: { "role": "dialog", "aria-labelledby": "newGameTxt" },
483 "class": { "card": true, "smallpad": true },
488 attrs: { "id": "close-newgame", "for": "modal-newgame" },
489 "class": { "modal-close": true },
494 attrs: { "id": "newGameTxt" },
495 "class": { "section": true },
496 domProps: { innerHTML: "New game" },
501 "class": { "section": true },
502 domProps: { innerHTML: "Waiting for opponent..." },
510 elementArray
= elementArray
.concat(modalNewgame
);
511 const modalFenEdit
= [
514 attrs: { "id": "modal-fenedit", type: "checkbox" },
515 "class": { "modal": true },
519 attrs: { "role": "dialog", "aria-labelledby": "titleFenedit" },
524 "class": { "card": true, "smallpad": true },
529 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
530 "class": { "modal-close": true },
535 attrs: { "id": "titleFenedit" },
536 "class": { "section": true },
537 domProps: { innerHTML: "Position + flags (FEN):" },
545 value: VariantRules
.GenRandInitFen(),
553 const fen
= document
.getElementById("input-fen").value
;
554 document
.getElementById("modal-fenedit").checked
= false;
555 this.newGame("friend", fen
);
558 domProps: { innerHTML: "Ok" },
565 document
.getElementById("input-fen").value
=
566 VariantRules
.GenRandInitFen();
569 domProps: { innerHTML: "Random" },
577 elementArray
= elementArray
.concat(modalFenEdit
);
578 const modalSettings
= [
581 attrs: { "id": "modal-settings", type: "checkbox" },
582 "class": { "modal": true },
586 attrs: { "role": "dialog", "aria-labelledby": "settingsTitle" },
591 "class": { "card": true, "smallpad": true },
596 attrs: { "id": "close-settings", "for": "modal-settings" },
597 "class": { "modal-close": true },
602 attrs: { "id": "settingsTitle" },
603 "class": { "section": true },
604 domProps: { innerHTML: "Preferences" },
610 //h('legend', { domProps: { innerHTML: "Legend title" } }),
613 attrs: { for: "setHints" },
614 domProps: { innerHTML: "Show hints?" },
624 on: { "change": this.toggleHints
},
634 attrs: { for: "selectColor" },
635 domProps: { innerHTML: "Board colors" },
640 attrs: { "id": "selectColor" },
641 on: { "change": this.setColor
},
650 attrs: { "selected": this.color
=="lichess" },
659 attrs: { "selected": this.color
=="chesscom" },
665 "value": "chesstempo",
668 attrs: { "selected": this.color
=="chesstempo" },
680 attrs: { for: "selectSound" },
681 domProps: { innerHTML: "Play sounds?" },
686 attrs: { "id": "selectSound" },
687 on: { "change": this.setSound
},
696 attrs: { "selected": this.sound
==0 },
705 attrs: { "selected": this.sound
==1 },
714 attrs: { "selected": this.sound
==2 },
726 elementArray
= elementArray
.concat(modalSettings
);
727 const actions
= h('div',
729 attrs: { "id": "actions" },
730 'class': { 'text-center': true },
734 elementArray
.push(actions
);
735 if (this.score
!= "*" && this.pgnTxt
.length
> 0)
740 attrs: { id: "pgn-div" },
741 "class": { "section-content": true },
754 attrs: { id: "pgn-game" },
755 domProps: { innerHTML: this.pgnTxt
}
760 attrs: { "id": "downloadBtn" },
761 on: { click: this.download
},
762 domProps: { innerHTML: "Download game" },
769 else if (this.mode
!= "idle")
771 if (this.mode
== "problem")
773 // Show problem solution (on click)
777 attrs: { id: "solution-div" },
778 "class": { "section-content": true },
783 domProps: { innerHTML: "Show solution" },
784 on: { click: this.toggleShowSolution
},
789 attrs: { id: "problem-solution" },
790 domProps: { innerHTML: this.problem
.solution
}
801 attrs: { id: "fen-div" },
802 "class": { "section-content": true },
807 attrs: { id: "fen-string" },
808 domProps: { innerHTML: this.vr
.getBaseFen() }
821 "col-md-offset-2":true,
823 "col-lg-offset-3":true,
825 // NOTE: click = mousedown + mouseup
827 mousedown: this.mousedown
,
828 mousemove: this.mousemove
,
829 mouseup: this.mouseup
,
830 touchstart: this.mousedown
,
831 touchmove: this.mousemove
,
832 touchend: this.mouseup
,
839 endgameMessage: function() {
840 let eogMessage
= "Unfinished";
844 eogMessage
= "White win";
847 eogMessage
= "Black win";
856 created: function() {
857 const url
= socketUrl
;
858 const humanContinuation
= (localStorage
.getItem("variant") === variant
);
859 const computerContinuation
= (localStorage
.getItem("comp-variant") === variant
);
860 this.myid
= (humanContinuation
? localStorage
.getItem("myid") : getRandString());
861 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
862 const socketOpenListener
= () => {
863 if (humanContinuation
) //game VS human has priority
865 const fen
= localStorage
.getItem("fen");
866 const mycolor
= localStorage
.getItem("mycolor");
867 const oppid
= localStorage
.getItem("oppid");
868 const moves
= JSON
.parse(localStorage
.getItem("moves"));
869 this.newGame("human", fen
, mycolor
, oppid
, moves
, true);
870 // Send ping to server (answer pong if opponent is connected)
871 this.conn
.send(JSON
.stringify({code:"ping",oppid:this.oppid
}));
873 else if (computerContinuation
)
875 const fen
= localStorage
.getItem("comp-fen");
876 const mycolor
= localStorage
.getItem("comp-mycolor");
877 const moves
= JSON
.parse(localStorage
.getItem("comp-moves"));
878 this.newGame("computer", fen
, mycolor
, undefined, moves
, true);
881 const socketMessageListener
= msg
=> {
882 const data
= JSON
.parse(msg
.data
);
886 // We opened another tab on the same game
889 alert("Already playing a game in this variant on another tab!");
891 case "newgame": //opponent found
892 // oppid: opponent socket ID
893 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
895 case "newmove": //..he played!
896 this.play(data
.move, "animate");
898 case "pong": //received if we sent a ping (game still alive on our side)
899 this.oppConnected
= true;
900 const L
= this.vr
.moves
.length
;
901 // Send our "last state" informations to opponent
902 this.conn
.send(JSON
.stringify({
905 lastMove:L
>0?this.vr
.moves
[L
-1]:undefined,
909 case "lastate": //got opponent infos about last move (we might have resigned)
910 if (this.mode
!="human" || this.oppid
!=data
.oppid
)
913 this.conn
.send(JSON
.stringify({
920 else if (data
.movesCount
< 0)
923 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
925 else if (data
.movesCount
< this.vr
.moves
.length
)
927 // We must tell last move to opponent
928 const L
= this.vr
.moves
.length
;
929 this.conn
.send(JSON
.stringify({
932 lastMove:this.vr
.moves
[L
-1],
936 else if (data
.movesCount
> this.vr
.moves
.length
) //just got last move from him
937 this.play(data
.lastMove
, "animate");
939 case "resign": //..you won!
940 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
942 // TODO: also use (dis)connect info to count online players?
945 if (this.mode
== "human" && this.oppid
== data
.id
)
946 this.oppConnected
= (data
.code
== "connect");
950 const socketCloseListener
= () => {
951 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
952 this.conn
.addEventListener('open', socketOpenListener
);
953 this.conn
.addEventListener('message', socketMessageListener
);
954 this.conn
.addEventListener('close', socketCloseListener
);
956 this.conn
.onopen
= socketOpenListener
;
957 this.conn
.onmessage
= socketMessageListener
;
958 this.conn
.onclose
= socketCloseListener
;
959 // Listen to keyboard left/right to navigate in game
960 document
.onkeydown
= event
=> {
961 if (this.mode
== "idle" && !!this.vr
&& this.vr
.moves
.length
> 0
962 && [37,39].includes(event
.keyCode
))
964 event
.preventDefault();
965 if (event
.keyCode
== 37) //Back
971 // Computer moves web worker logic:
972 this.compWorker
.postMessage(["scripts",variant
]);
974 this.compWorker
.onmessage = function(e
) {
975 const compMove
= e
.data
;
976 // (first move) HACK: small delay to avoid selecting elements
977 // before they appear on page:
978 const delay
= Math
.max(500-(Date
.now()-self
.timeStart
), 0);
980 if (self
.mode
== "computer") //Warning: mode could have changed!
981 self
.play(compMove
, "animate")
986 toggleShowSolution: function() {
987 let problemSolution
= document
.getElementById("problem-solution");
988 problemSolution
.style
.display
=
989 !problemSolution
.style
.display
|| problemSolution
.style
.display
== "none"
993 download: function() {
994 let content
= document
.getElementById("pgn-game").innerHTML
;
995 content
= content
.replace(/<br>/g, "\n");
996 // Prepare and trigger download link
997 let downloadAnchor
= document
.getElementById("download");
998 downloadAnchor
.setAttribute("download", "game.pgn");
999 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
1000 encodeURIComponent(content
);
1001 downloadAnchor
.click();
1003 showScoreMsg: function() {
1004 let modalBox
= document
.getElementById("modal-eog");
1005 modalBox
.checked
= true;
1006 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1008 endGame: function(score
) {
1010 this.showScoreMsg();
1011 // Variants may have special PGN structure (so next function isn't defined here)
1012 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
1013 if (["human","computer"].includes(this.mode
))
1014 this.clearStorage();
1016 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
1019 setStorage: function() {
1020 if (this.mode
=="human")
1022 localStorage
.setItem("myid", this.myid
);
1023 localStorage
.setItem("oppid", this.oppid
);
1025 // 'prefix' = "comp-" to resume games vs. computer
1026 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1027 localStorage
.setItem(prefix
+"variant", variant
);
1028 localStorage
.setItem(prefix
+"mycolor", this.mycolor
);
1029 localStorage
.setItem(prefix
+"fenStart", this.fenStart
);
1030 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1031 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1033 updateStorage: function() {
1034 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1035 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1036 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1038 clearStorage: function() {
1039 if (this.mode
=="human")
1041 delete localStorage
["myid"];
1042 delete localStorage
["oppid"];
1044 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1045 delete localStorage
[prefix
+"variant"];
1046 delete localStorage
[prefix
+"mycolor"];
1047 delete localStorage
[prefix
+"fenStart"];
1048 delete localStorage
[prefix
+"fen"];
1049 delete localStorage
[prefix
+"moves"];
1051 // HACK because mini-css tooltips are persistent after click...
1052 getRidOfTooltip: function(elt
) {
1053 elt
.style
.visibility
= "hidden";
1054 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
1056 showSettings: function(e
) {
1057 this.getRidOfTooltip(e
.currentTarget
);
1058 document
.getElementById("modal-settings").checked
= true;
1060 toggleHints: function() {
1061 this.hints
= !this.hints
;
1062 setCookie("hints", this.hints
? "1" : "0");
1064 setColor: function(e
) {
1065 this.color
= e
.target
.options
[e
.target
.selectedIndex
].value
;
1066 setCookie("color", this.color
);
1068 setSound: function(e
) {
1069 this.sound
= parseInt(e
.target
.options
[e
.target
.selectedIndex
].value
);
1070 setCookie("sound", this.sound
);
1072 clickGameSeek: function(e
) {
1073 this.getRidOfTooltip(e
.currentTarget
);
1074 if (this.mode
== "human")
1075 return; //no newgame while playing
1078 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
1082 this.newGame("human");
1084 clickComputerGame: function(e
) {
1085 this.getRidOfTooltip(e
.currentTarget
);
1086 if (this.mode
== "human")
1087 return; //no newgame while playing
1088 this.newGame("computer");
1090 clickFriendGame: function(e
) {
1091 this.getRidOfTooltip(e
.currentTarget
);
1092 document
.getElementById("modal-fenedit").checked
= true;
1094 resign: function(e
) {
1095 this.getRidOfTooltip(e
.currentTarget
);
1096 if (this.mode
== "human" && this.oppConnected
)
1099 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
1100 } catch (INVALID_STATE_ERR
) {
1101 return; //socket is not ready (and not yet reconnected)
1104 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
1106 newGame: function(mode
, fenInit
, color
, oppId
, moves
, continuation
) {
1107 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
1108 console
.log(fen
); //DEBUG
1109 if (mode
=="human" && !oppId
)
1111 const storageVariant
= localStorage
.getItem("variant");
1112 if (!!storageVariant
&& storageVariant
!== variant
)
1113 return alert("Finish your " + storageVariant
+ " game first!");
1114 // Send game request and wait..
1116 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
1117 } catch (INVALID_STATE_ERR
) {
1118 return; //nothing achieved
1121 let modalBox
= document
.getElementById("modal-newgame");
1122 modalBox
.checked
= true;
1123 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1126 if (mode
== "computer" && !continuation
)
1128 const storageVariant
= localStorage
.getItem("comp-variant");
1129 if (!!storageVariant
&& storageVariant
!== variant
)
1131 if (!confirm("Unfinished " + storageVariant
+
1132 " computer game will be erased"))
1138 if (this.mode
== "computer" && mode
== "human")
1140 // Save current computer game to resume it later
1143 this.vr
= new VariantRules(fen
, moves
|| []);
1145 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
1147 if (continuation
&& moves
.length
> 0) //NOTE: "continuation": redundant test
1149 const lastMove
= moves
[moves
.length
-1];
1150 this.vr
.undo(lastMove
);
1151 this.incheck
= this.vr
.getCheckSquares(lastMove
);
1152 this.vr
.play(lastMove
, "ingame");
1158 const prefix
= (mode
=="computer" ? "comp-" : "");
1159 this.fenStart
= localStorage
.getItem(prefix
+"fenStart");
1162 this.fenStart
= V
.ParseFen(fen
).position
; //this is enough
1166 if (!continuation
) //not playing sound on game continuation
1168 if (this.sound
>= 1)
1169 new Audio("/sounds/newgame.mp3").play().catch(err
=> {});
1170 document
.getElementById("modal-newgame").checked
= false;
1173 this.oppConnected
= !continuation
;
1174 this.mycolor
= color
;
1176 this.setStorage(); //in case of interruptions
1178 else if (mode
== "computer")
1180 this.compWorker
.postMessage(["init",this.vr
.getFen()]);
1181 this.mycolor
= Math
.random() < 0.5 ? 'w' : 'b';
1182 if (this.mycolor
== 'b')
1183 this.playComputerMove();
1185 //else: against a (IRL) friend or problem solving: nothing more to do
1187 playComputerMove: function() {
1188 this.timeStart
= Date
.now();
1189 this.compWorker
.postMessage(["askmove"]);
1191 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1192 getSquareId: function(o
) {
1193 // NOTE: a separator is required to allow any size of board
1194 return "sq-" + o
.x
+ "-" + o
.y
;
1197 getSquareFromId: function(id
) {
1198 let idParts
= id
.split('-');
1199 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
1201 mousedown: function(e
) {
1202 e
= e
|| window
.event
;
1204 let elem
= e
.target
;
1205 while (!ingame
&& elem
!== null)
1207 if (elem
.classList
.contains("game"))
1212 elem
= elem
.parentElement
;
1214 if (!ingame
) //let default behavior (click on button...)
1216 e
.preventDefault(); //disable native drag & drop
1217 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
1219 // Next few lines to center the piece on mouse cursor
1220 let rect
= e
.target
.parentNode
.getBoundingClientRect();
1222 x: rect
.x
+ rect
.width
/2,
1223 y: rect
.y
+ rect
.width
/2,
1224 id: e
.target
.parentNode
.id
1226 this.selectedPiece
= e
.target
.cloneNode();
1227 this.selectedPiece
.style
.position
= "absolute";
1228 this.selectedPiece
.style
.top
= 0;
1229 this.selectedPiece
.style
.display
= "inline-block";
1230 this.selectedPiece
.style
.zIndex
= 3000;
1231 const startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1232 this.possibleMoves
= [];
1233 if (this.mode
!= "idle")
1235 const color
= ["friend","problem"].includes(this.mode
)
1238 if (this.vr
.canIplay(color
,startSquare
))
1239 this.possibleMoves
= this.vr
.getPossibleMovesFrom(startSquare
);
1241 // Next line add moving piece just after current image
1242 // (required for Crazyhouse reserve)
1243 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1246 mousemove: function(e
) {
1247 if (!this.selectedPiece
)
1249 e
= e
|| window
.event
;
1250 // If there is an active element, move it around
1251 if (!!this.selectedPiece
)
1253 const [offsetX
,offsetY
] = !!e
.clientX
1254 ? [e
.clientX
,e
.clientY
] //desktop browser
1255 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1256 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1257 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1260 mouseup: function(e
) {
1261 if (!this.selectedPiece
)
1263 e
= e
|| window
.event
;
1264 // Read drop target (or parentElement, parentNode... if type == "img")
1265 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1266 const [offsetX
,offsetY
] = !!e
.clientX
1267 ? [e
.clientX
,e
.clientY
]
1268 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1269 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1270 this.selectedPiece
.style
.zIndex
= 3000;
1271 // Next condition: classList.contains(piece) fails because of marks
1272 while (landing
.tagName
== "IMG")
1273 landing
= landing
.parentNode
;
1274 if (this.start
.id
== landing
.id
)
1276 // A click: selectedPiece and possibleMoves are already filled
1279 // OK: process move attempt
1280 let endSquare
= this.getSquareFromId(landing
.id
);
1281 let moves
= this.findMatchingMoves(endSquare
);
1282 this.possibleMoves
= [];
1283 if (moves
.length
> 1)
1284 this.choices
= moves
;
1285 else if (moves
.length
==1)
1286 this.play(moves
[0]);
1287 // Else: impossible move
1288 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1289 delete this.selectedPiece
;
1290 this.selectedPiece
= null;
1292 findMatchingMoves: function(endSquare
) {
1293 // Run through moves list and return the matching set (if promotions...)
1295 this.possibleMoves
.forEach(function(m
) {
1296 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1301 animateMove: function(move) {
1302 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1303 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1304 let rectStart
= startSquare
.getBoundingClientRect();
1305 let rectEnd
= endSquare
.getBoundingClientRect();
1306 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1308 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1309 // HACK for animation (with positive translate, image slides "under background")
1310 // Possible improvement: just alter squares on the piece's way...
1311 squares
= document
.getElementsByClassName("board");
1312 for (let i
=0; i
<squares
.length
; i
++)
1314 let square
= squares
.item(i
);
1315 if (square
.id
!= this.getSquareId(move.start
))
1316 square
.style
.zIndex
= "-1";
1318 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1319 translation
.y
+ "px)";
1320 movingPiece
.style
.transitionDuration
= "0.2s";
1321 movingPiece
.style
.zIndex
= "3000";
1323 for (let i
=0; i
<squares
.length
; i
++)
1324 squares
.item(i
).style
.zIndex
= "auto";
1325 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1329 play: function(move, programmatic
) {
1332 // Navigate after game is over
1333 if (this.cursor
>= this.vr
.moves
.length
)
1334 return; //already at the end
1335 move = this.vr
.moves
[this.cursor
++];
1337 if (!!programmatic
) //computer or human opponent
1339 this.animateMove(move);
1342 // Not programmatic, or animation is over
1343 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1344 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1345 if (this.sound
== 2)
1346 new Audio("/sounds/chessmove1.mp3").play().catch(err
=> {});
1347 if (this.mode
!= "idle")
1349 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1350 this.vr
.play(move, "ingame");
1351 if (this.mode
== "computer")
1353 // Send the move to web worker
1354 this.compWorker
.postMessage(["newmove",move]);
1359 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1360 this.$forceUpdate(); //TODO: ?!
1362 if (["human","computer"].includes(this.mode
))
1363 this.updateStorage(); //after our moves and opponent moves
1364 if (this.mode
!= "idle")
1366 const eog
= this.vr
.checkGameOver();
1369 if (["human","computer"].includes(this.mode
))
1373 // Just show score on screen (allow undo)
1375 this.showScoreMsg();
1379 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
)
1380 this.playComputerMove();
1383 // Navigate after game is over
1384 if (this.cursor
== 0)
1385 return; //already at the beginning
1386 if (this.cursor
== this.vr
.moves
.length
)
1387 this.incheck
= []; //in case of...
1388 const move = this.vr
.moves
[--this.cursor
];
1389 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1390 this.$forceUpdate(); //TODO: ?!
1392 undoInGame: function() {
1393 const lm
= this.vr
.lastMove
;
1397 const lmBefore
= this.vr
.lastMove
;
1400 this.vr
.undo(lmBefore
);
1401 this.incheck
= this.vr
.getCheckSquares(lmBefore
);
1402 this.vr
.play(lmBefore
, "ingame");