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, chat, friend, problem, computer or idle (if not playing)
15 myid: "", //our ID, always set
16 oppid: "", //opponent ID in case of HH game
17 gameId: "", //useful if opponent started other human games after we disconnected
18 myname: localStorage
["username"] || "anonymous",
19 oppName: "anonymous", //opponent name, revealed after a game (if provided)
20 chats: [], //chat messages after human game
26 hints: (!localStorage
["hints"] ? true : localStorage
["hints"] === "1"),
27 color: localStorage
["color"] || "lichess", //lichess, chesscom or chesstempo
28 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
29 sound: parseInt(localStorage
["sound"] || "2"),
30 // Web worker to play computer moves without freezing interface:
31 compWorker: new Worker('/javascripts/playCompMove.js'),
32 timeStart: undefined, //time when computer starts thinking
36 problem: function(p
) {
37 // 'problem' prop changed: update board state
38 this.newGame("problem", p
.fen
, V
.ParseFen(p
.fen
).turn
);
42 const [sizeX
,sizeY
] = [V
.size
.x
,V
.size
.y
];
43 // Precompute hints squares to facilitate rendering
44 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
45 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
46 // Also precompute in-check squares
47 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
48 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
49 let elementArray
= [];
54 on: { click: this.clickGameSeek
},
55 attrs: { "aria-label": translations
['New live game'] },
60 "playing": this.mode
== "human",
64 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
66 if (variant
!="Dark" && ["idle","chat","computer"].includes(this.mode
))
71 on: { click: this.clickComputerGame
},
72 attrs: { "aria-label": translations
['New game versus computer'] },
76 "playing": this.mode
== "computer",
80 [h('i', { 'class': { "material-icons": true } }, "computer")])
83 if (variant
!="Dark" && ["idle","chat","friend"].includes(this.mode
))
88 on: { click: this.clickFriendGame
},
89 attrs: { "aria-label": translations
['Analysis mode'] },
93 "playing": this.mode
== "friend",
97 [h('i', { 'class': { "material-icons": true } }, "people")])
102 const square00
= document
.getElementById("sq-0-0");
103 const squareWidth
= !!square00
104 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
106 const settingsBtnElt
= document
.getElementById("settingsBtn");
107 const settingsStyle
= !!settingsBtnElt
108 ? window
.getComputedStyle(settingsBtnElt
)
109 : {width:"46px", height:"26px"};
110 const [indicWidth
,indicHeight
] = //[44,24];
112 // NOTE: -2 for border
113 parseFloat(settingsStyle
.width
.slice(0,-2)) - 2,
114 parseFloat(settingsStyle
.height
.slice(0,-2)) - 2
116 let aboveBoardElts
= [];
117 if (["chat","human"].includes(this.mode
))
119 const connectedIndic
= h(
124 "connected": this.oppConnected
,
125 "disconnected": !this.oppConnected
,
128 "width": indicWidth
+ "px",
129 "height": indicHeight
+ "px",
133 aboveBoardElts
.push(connectedIndic
);
135 if (this.mode
== "chat")
137 const chatButton
= h(
140 on: { click: this.startChat
},
142 "aria-label": translations
['Start chat'],
152 [h('i', { 'class': { "material-icons": true } }, "chat")]
154 aboveBoardElts
.push(chatButton
);
156 else if (this.mode
== "computer")
158 const clearButton
= h(
161 on: { click: this.clearComputerGame
},
163 "aria-label": translations
['Clear game versus computer'],
173 [h('i', { 'class': { "material-icons": true } }, "clear")]
175 aboveBoardElts
.push(clearButton
);
182 "white-turn": this.vr
.turn
=="w",
183 "black-turn": this.vr
.turn
=="b",
186 "width": indicWidth
+ "px",
187 "height": indicHeight
+ "px",
191 aboveBoardElts
.push(turnIndic
);
192 const settingsBtn
= h(
195 on: { click: this.showSettings
},
197 "aria-label": translations
['Settings'],
207 [h('i', { 'class': { "material-icons": true } }, "settings")]
209 aboveBoardElts
.push(settingsBtn
);
212 { "class": { "aboveboard-wrapper": true } },
216 if (this.mode
== "problem")
218 // Show problem instructions
222 attrs: { id: "instructions-div" },
225 "section-content": true,
231 attrs: { id: "problem-instructions" },
232 domProps: { innerHTML: this.problem
.instructions
}
239 const choices
= h('div',
241 attrs: { "id": "choices" },
242 'class': { 'row': true },
244 "display": this.choices
.length
>0?"block":"none",
245 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
246 "width": (this.choices
.length
* squareWidth
) + "px",
247 "height": squareWidth
+ "px",
250 this.choices
.map( m
=> { //a "choice" is a move
255 ['board'+sizeY
]: true,
258 'width': (100/this.choices
.length
) + "%",
259 'padding-bottom': (100/this.choices
.length
) + "%",
264 attrs: { "src": '/images/pieces/' +
265 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
266 'class': { 'choice-piece': true },
268 "click": e
=> { this.play(m
); this.choices
=[]; },
269 // NOTE: add 'touchstart' event to fix a problem on smartphones
270 "touchstart": e
=> { this.play(m
); this.choices
=[]; },
277 // Create board element (+ reserves if needed by variant or mode)
278 const lm
= this.vr
.lastMove
;
279 const showLight
= this.hints
&&
280 (!["idle","chat"].includes(this.mode
) || this.cursor
==this.vr
.moves
.length
);
281 const gameDiv
= h('div',
288 [_
.range(sizeX
).map(i
=> {
289 let ci
= (this.mycolor
=='w' ? i : sizeX
-i
-1);
296 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
298 _
.range(sizeY
).map(j
=> {
299 let cj
= (this.mycolor
=='w' ? j : sizeY
-j
-1);
301 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
&& (variant
!="Dark"
302 || this.score
!="*" || this.vr
.isEnlightened(ci
,cj
,this.mycolor
)))
310 'ghost': !!this.selectedPiece
311 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
314 src: "/images/pieces/" +
315 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
321 if (this.hints
&& hintSquares
[ci
][cj
])
331 src: "/images/mark.svg",
342 ['board'+sizeY
]: true,
343 'light-square': (i
+j
)%2==0,
344 'dark-square': (i
+j
)%2==1,
346 'in-shadow': variant
=="Dark" && this.score
=="*"
347 && !this.vr
.isEnlightened(ci
,cj
,this.mycolor
),
348 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
349 'incheck': showLight
&& incheckSq
[ci
][cj
],
352 id: this.getSquareId({x:ci
,y:cj
}),
361 if (!["idle","chat"].includes(this.mode
))
366 on: { click: this.resign
},
367 attrs: { "aria-label": translations
['Resign'] },
373 [h('i', { 'class': { "material-icons": true } }, "flag")])
376 else if (this.vr
.moves
.length
> 0)
378 // A game finished, and another is not started yet: allow navigation
379 actionArray
= actionArray
.concat([
382 on: { click: e
=> this.undo() },
383 attrs: { "aria-label": translations
['Undo'] },
389 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
392 on: { click: e
=> this.play() },
393 attrs: { "aria-label": translations
['Play'] },
399 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
403 if (["friend","problem"].includes(this.mode
))
405 actionArray
= actionArray
.concat(
409 on: { click: this.undoInGame
},
410 attrs: { "aria-label": translations
['Undo'] },
416 [h('i', { 'class': { "material-icons": true } }, "undo")]
420 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
421 attrs: { "aria-label": translations
['Flip board'] },
427 [h('i', { 'class': { "material-icons": true } }, "cached")]
431 elementArray
.push(gameDiv
);
432 if (!!this.vr
.reserve
)
434 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
435 let myReservePiecesArray
= [];
436 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
438 myReservePiecesArray
.push(h('div',
440 'class': {'board':true, ['board'+sizeY
+'-reserve']:true},
441 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
446 'class': {"piece":true, "reserve":true},
448 "src": "/images/pieces/" +
449 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
453 {"class": { "reserve-count": true } },
454 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
458 let oppReservePiecesArray
= [];
459 const oppCol
= this.vr
.getOppCol(this.mycolor
);
460 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
462 oppReservePiecesArray
.push(h('div',
464 'class': {'board':true, ['board'+sizeY
+'-reserve']:true},
465 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
470 'class': {"piece":true, "reserve":true},
472 "src": "/images/pieces/" +
473 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
477 {"class": { "reserve-count": true } },
478 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
482 let reserves
= h('div',
494 "reserve-row-1": true,
500 { 'class': { 'row': true }},
501 oppReservePiecesArray
505 elementArray
.push(reserves
);
510 attrs: { "id": "modal-eog", type: "checkbox" },
511 "class": { "modal": true },
515 attrs: { "role": "dialog", "aria-labelledby": "eogMessage" },
530 attrs: { "for": "modal-eog" },
531 "class": { "modal-close": true },
536 attrs: { "id": "eogMessage" },
537 "class": { "section": true },
538 domProps: { innerHTML: this.endgameMessage
},
546 elementArray
= elementArray
.concat(modalEog
);
548 const modalFenEdit
= [
551 attrs: { "id": "modal-fenedit", type: "checkbox" },
552 "class": { "modal": true },
556 attrs: { "role": "dialog", "aria-labelledby": "titleFenedit" },
561 "class": { "card": true, "smallpad": true },
566 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
567 "class": { "modal-close": true },
572 attrs: { "id": "titleFenedit" },
573 "class": { "section": true },
574 domProps: { innerHTML: translations
["Game state (FEN):"] },
582 value: VariantRules
.GenRandInitFen(),
590 const fen
= document
.getElementById("input-fen").value
;
591 document
.getElementById("modal-fenedit").checked
= false;
592 this.newGame("friend", fen
);
595 domProps: { innerHTML: translations
["Ok"] },
602 document
.getElementById("input-fen").value
=
603 VariantRules
.GenRandInitFen();
606 domProps: { innerHTML: translations
["Random"] },
614 elementArray
= elementArray
.concat(modalFenEdit
);
615 const modalSettings
= [
618 attrs: { "id": "modal-settings", type: "checkbox" },
619 "class": { "modal": true },
623 attrs: { "role": "dialog", "aria-labelledby": "settingsTitle" },
628 "class": { "card": true, "smallpad": true },
633 attrs: { "id": "close-settings", "for": "modal-settings" },
634 "class": { "modal-close": true },
639 attrs: { "id": "settingsTitle" },
640 "class": { "section": true },
641 domProps: { innerHTML: translations
["Preferences"] },
649 attrs: { for: "nameSetter" },
650 domProps: { innerHTML: translations
["My name is..."] },
660 on: { "change": this.setMyname
},
670 attrs: { for: "setHints" },
671 domProps: { innerHTML: translations
["Show hints?"] },
681 on: { "change": this.toggleHints
},
691 attrs: { for: "selectColor" },
692 domProps: { innerHTML: translations
["Board colors"] },
697 attrs: { "id": "selectColor" },
698 on: { "change": this.setColor
},
705 innerHTML: translations
["brown"]
707 attrs: { "selected": this.color
=="lichess" },
714 innerHTML: translations
["green"]
716 attrs: { "selected": this.color
=="chesscom" },
722 "value": "chesstempo",
723 innerHTML: translations
["blue"]
725 attrs: { "selected": this.color
=="chesstempo" },
737 attrs: { for: "selectSound" },
738 domProps: { innerHTML: translations
["Play sounds?"] },
743 attrs: { "id": "selectSound" },
744 on: { "change": this.setSound
},
751 innerHTML: translations
["None"]
753 attrs: { "selected": this.sound
==0 },
760 innerHTML: translations
["New game"]
762 attrs: { "selected": this.sound
==1 },
769 innerHTML: translations
["All"]
771 attrs: { "selected": this.sound
==2 },
783 elementArray
= elementArray
.concat(modalSettings
);
788 attrs: { "id": "close-chat", "for": "modal-chat" },
789 "class": { "modal-close": true },
794 attrs: { "id": "titleChat" },
795 "class": { "section": true },
796 domProps: { innerHTML: translations
["Chat with "] + this.oppName
},
800 for (let chat
of this.chats
)
806 "my-chatmsg": chat
.author
==this.myid
,
807 "opp-chatmsg": chat
.author
==this.oppid
,
809 domProps: { innerHTML: chat
.msg
}
814 chatEltsArray
= chatEltsArray
.concat([
820 placeholder: translations
["Type here"],
822 on: { keyup: this.trySendChat
}, //if key is 'enter'
827 attrs: { id: "sendChatBtn"},
828 on: { click: this.sendChat
},
829 domProps: { innerHTML: translations
["Send"] },
836 attrs: { "id": "modal-chat", type: "checkbox" },
837 "class": { "modal": true },
841 attrs: { "role": "dialog", "aria-labelledby": "titleChat" },
846 "class": { "card": true, "smallpad": true },
853 elementArray
= elementArray
.concat(modalChat
);
854 const actions
= h('div',
856 attrs: { "id": "actions" },
857 'class': { 'text-center': true },
861 elementArray
.push(actions
);
862 if (this.score
!= "*" && this.pgnTxt
.length
> 0)
867 attrs: { id: "pgn-div" },
868 "class": { "section-content": true },
881 attrs: { id: "pgn-game" },
882 domProps: { innerHTML: this.pgnTxt
}
887 attrs: { "id": "downloadBtn" },
888 on: { click: this.download
},
889 domProps: { innerHTML: translations
["Download game"] },
896 else if (this.mode
!= "idle")
898 if (this.mode
== "problem")
900 // Show problem solution (on click)
904 attrs: { id: "solution-div" },
905 "class": { "section-content": true },
910 "class": { clickable: true },
911 domProps: { innerHTML: translations
["Show solution"] },
912 on: { click: this.toggleShowSolution
},
917 attrs: { id: "problem-solution" },
918 domProps: { innerHTML: this.problem
.solution
}
925 if (variant
!= "Dark" || this.score
!="*")
931 attrs: { id: "fen-div" },
932 "class": { "section-content": true },
937 attrs: { id: "fen-string" },
938 domProps: { innerHTML: this.vr
.getBaseFen() },
939 "class": { "text-center": true },
953 "col-md-offset-1":true,
955 "col-lg-offset-2":true,
957 // NOTE: click = mousedown + mouseup
959 mousedown: this.mousedown
,
960 mousemove: this.mousemove
,
961 mouseup: this.mouseup
,
962 touchstart: this.mousedown
,
963 touchmove: this.mousemove
,
964 touchend: this.mouseup
,
971 endgameMessage: function() {
972 let eogMessage
= "Unfinished";
976 eogMessage
= translations
["White win"];
979 eogMessage
= translations
["Black win"];
982 eogMessage
= translations
["Draw"];
988 created: function() {
989 const url
= socketUrl
;
990 const humanContinuation
= (localStorage
.getItem("variant") === variant
);
991 const computerContinuation
= (localStorage
.getItem("comp-variant") === variant
);
992 this.myid
= (humanContinuation
? localStorage
.getItem("myid") : getRandString());
993 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
994 const socketOpenListener
= () => {
995 if (humanContinuation
) //game VS human has priority
996 this.continueGame("human");
997 else if (computerContinuation
)
998 this.continueGame("computer");
1000 const socketMessageListener
= msg
=> {
1001 const data
= JSON
.parse(msg
.data
);
1002 const L
= (!!this.vr
? this.vr
.moves
.length : 0);
1006 // Receive opponent's name
1007 this.oppName
= data
.name
;
1011 this.chats
.push({msg:data
.msg
, author:this.oppid
});
1014 // We opened another tab on the same game
1018 "Already playing a game in this variant on another tab!"]);
1020 case "newgame": //opponent found
1021 // oppid: opponent socket ID
1022 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
1024 case "newmove": //..he played!
1025 this.play(data
.move, "animate");
1027 case "pong": //received if we sent a ping (game still alive on our side)
1028 if (this.gameId
!= data
.gameId
)
1029 break; //games IDs don't match: definitely over...
1030 this.oppConnected
= true;
1031 // Send our "last state" informations to opponent
1032 this.conn
.send(JSON
.stringify({
1035 gameId: this.gameId
,
1036 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
1040 case "lastate": //got opponent infos about last move
1041 if (this.gameId
!= data
.gameId
)
1042 break; //games IDs don't match: nothing we can do...
1043 // OK, opponent still in game (which might be over)
1044 if (this.mode
!= "human")
1046 // We finished the game (any result possible)
1047 this.conn
.send(JSON
.stringify({
1050 gameId: this.gameId
,
1054 else if (!!data
.score
) //opponent finished the game
1055 this.endGame(data
.score
);
1056 else if (data
.movesCount
< L
)
1058 // We must tell last move to opponent
1059 this.conn
.send(JSON
.stringify({
1062 lastMove: this.vr
.moves
[L
-1],
1066 else if (data
.movesCount
> L
) //just got last move from him
1067 this.play(data
.lastMove
, "animate");
1069 case "resign": //..you won!
1070 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
1072 // TODO: also use (dis)connect info to count online players?
1075 if (["human","chat"].includes(this.mode
) && this.oppid
== data
.id
)
1076 this.oppConnected
= (data
.code
== "connect");
1077 if (this.oppConnected
&& this.mode
== "chat")
1079 // Send our name to the opponent, in case of he hasn't it
1080 this.conn
.send(JSON
.stringify({
1081 code:"myname", name:this.myname
, oppid: this.oppid
}));
1086 const socketCloseListener
= () => {
1087 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
1088 this.conn
.addEventListener('open', socketOpenListener
);
1089 this.conn
.addEventListener('message', socketMessageListener
);
1090 this.conn
.addEventListener('close', socketCloseListener
);
1092 this.conn
.onopen
= socketOpenListener
;
1093 this.conn
.onmessage
= socketMessageListener
;
1094 this.conn
.onclose
= socketCloseListener
;
1095 // Listen to keyboard left/right to navigate in game
1096 document
.onkeydown
= event
=> {
1097 if (["idle","chat"].includes(this.mode
) &&
1098 !!this.vr
&& this.vr
.moves
.length
> 0 && [37,39].includes(event
.keyCode
))
1100 event
.preventDefault();
1101 if (event
.keyCode
== 37) //Back
1107 // Computer moves web worker logic:
1108 this.compWorker
.postMessage(["scripts",variant
]);
1110 this.compWorker
.onmessage = function(e
) {
1111 let compMove
= e
.data
;
1112 compMove
.computer
= true; //TODO: imperfect attempt to avoid ghost move
1113 // (first move) HACK: small delay to avoid selecting elements
1114 // before they appear on page:
1115 const delay
= Math
.max(500-(Date
.now()-self
.timeStart
), 0);
1117 if (self
.mode
== "computer") //warning: mode could have changed!
1118 self
.play(compMove
, "animate")
1123 setMyname: function(e
) {
1124 this.myname
= e
.target
.value
;
1125 localStorage
["username"] = this.myname
;
1127 trySendChat: function(e
) {
1128 if (e
.keyCode
== 13) //'enter' key
1131 sendChat: function() {
1132 let chatInput
= document
.getElementById("input-chat");
1133 const chatTxt
= chatInput
.value
;
1134 chatInput
.value
= "";
1135 this.chats
.push({msg:chatTxt
, author:this.myid
});
1136 this.conn
.send(JSON
.stringify({
1137 code:"newchat", oppid: this.oppid
, msg: chatTxt
}));
1139 toggleShowSolution: function() {
1140 let problemSolution
= document
.getElementById("problem-solution");
1141 problemSolution
.style
.display
=
1142 !problemSolution
.style
.display
|| problemSolution
.style
.display
== "none"
1146 download: function() {
1147 let content
= document
.getElementById("pgn-game").innerHTML
;
1148 content
= content
.replace(/<br>/g, "\n");
1149 // Prepare and trigger download link
1150 let downloadAnchor
= document
.getElementById("download");
1151 downloadAnchor
.setAttribute("download", "game.pgn");
1152 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
1153 encodeURIComponent(content
);
1154 downloadAnchor
.click();
1156 showScoreMsg: function() {
1157 let modalBox
= document
.getElementById("modal-eog");
1158 modalBox
.checked
= true;
1159 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1161 endGame: function(score
) {
1163 if (["human","computer"].includes(this.mode
))
1165 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1166 localStorage
.setItem(prefix
+"score", score
);
1168 this.showScoreMsg();
1169 // Variants may have special PGN structure (so next function isn't defined here)
1170 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
1171 if (this.mode
== "human" && this.oppConnected
)
1173 // Send our nickname to opponent
1174 this.conn
.send(JSON
.stringify({
1175 code:"myname", name:this.myname
, oppid:this.oppid
}));
1177 this.mode
= (this.mode
=="human" ? "chat" : "idle");
1178 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
1180 setStorage: function() {
1181 if (this.mode
=="human")
1183 localStorage
.setItem("myid", this.myid
);
1184 localStorage
.setItem("oppid", this.oppid
);
1185 localStorage
.setItem("gameId", this.gameId
);
1187 // 'prefix' = "comp-" to resume games vs. computer
1188 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1189 localStorage
.setItem(prefix
+"variant", variant
);
1190 localStorage
.setItem(prefix
+"mycolor", this.mycolor
);
1191 localStorage
.setItem(prefix
+"fenStart", this.fenStart
);
1192 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1193 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1194 localStorage
.setItem(prefix
+"score", "*");
1196 updateStorage: function() {
1197 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1198 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1199 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1200 if (this.score
!= "*")
1201 localStorage
.setItem(prefix
+"score", this.score
);
1203 // "computer mode" clearing is done through the menu
1204 clearStorage: function() {
1205 if (["human","chat"].includes(this.mode
))
1207 delete localStorage
["myid"];
1208 delete localStorage
["oppid"];
1209 delete localStorage
["gameId"];
1211 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1212 delete localStorage
[prefix
+"variant"];
1213 delete localStorage
[prefix
+"mycolor"];
1214 delete localStorage
[prefix
+"fenStart"];
1215 delete localStorage
[prefix
+"moves"];
1216 delete localStorage
[prefix
+"fen"];
1217 delete localStorage
[prefix
+"score"];
1219 // HACK because mini-css tooltips are persistent after click...
1220 // NOTE: seems to work only in chrome/chromium. TODO...
1221 getRidOfTooltip: function(elt
) {
1222 elt
.style
.visibility
= "hidden";
1223 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
1225 startChat: function(e
) {
1226 this.getRidOfTooltip(e
.currentTarget
);
1227 document
.getElementById("modal-chat").checked
= true;
1229 clearComputerGame: function(e
) {
1230 this.getRidOfTooltip(e
.currentTarget
);
1231 this.clearStorage(); //this.mode=="computer" (already checked)
1232 location
.reload(); //to see clearing effects
1234 showSettings: function(e
) {
1235 this.getRidOfTooltip(e
.currentTarget
);
1236 document
.getElementById("modal-settings").checked
= true;
1238 toggleHints: function() {
1239 this.hints
= !this.hints
;
1240 localStorage
["hints"] = (this.hints
? "1" : "0");
1242 setColor: function(e
) {
1243 this.color
= e
.target
.options
[e
.target
.selectedIndex
].value
;
1244 localStorage
["color"] = this.color
;
1246 setSound: function(e
) {
1247 this.sound
= parseInt(e
.target
.options
[e
.target
.selectedIndex
].value
);
1248 localStorage
["sound"] = this.sound
;
1250 clickGameSeek: function(e
) {
1251 this.getRidOfTooltip(e
.currentTarget
);
1252 if (this.mode
== "human")
1253 return; //no newgame while playing
1256 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
1260 this.newGame("human");
1262 clickComputerGame: function(e
) {
1263 this.getRidOfTooltip(e
.currentTarget
);
1264 this.newGame("computer");
1266 clickFriendGame: function(e
) {
1267 this.getRidOfTooltip(e
.currentTarget
);
1268 document
.getElementById("modal-fenedit").checked
= true;
1270 resign: function(e
) {
1271 this.getRidOfTooltip(e
.currentTarget
);
1272 if (this.mode
== "human" && this.oppConnected
)
1275 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
1276 } catch (INVALID_STATE_ERR
) {
1277 return; //socket is not ready (and not yet reconnected)
1280 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
1282 newGame: function(mode
, fenInit
, color
, oppId
) {
1283 let fen
= fenInit
|| VariantRules
.GenRandInitFen();
1284 console
.log(fen
); //DEBUG
1285 if (mode
=="human" && !oppId
)
1287 const storageVariant
= localStorage
.getItem("variant");
1288 if (!!storageVariant
&& storageVariant
!== variant
)
1290 return alert(translations
["Finish your "] +
1291 storageVariant
+ translations
[" game first!"]);
1293 // Send game request and wait..
1295 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
1296 } catch (INVALID_STATE_ERR
) {
1297 return; //nothing achieved
1300 let modalBox
= document
.getElementById("modal-newgame");
1301 modalBox
.checked
= true;
1302 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1305 if (["human","chat"].includes(this.mode
))
1307 // Start a new game vs. another human (or...) => forget about current one
1308 this.clearStorage();
1310 if (mode
== "computer")
1312 const storageVariant
= localStorage
.getItem("comp-variant");
1313 if (!!storageVariant
)
1315 const score
= localStorage
.getItem("comp-score");
1316 if (storageVariant
!== variant
&& score
== "*")
1318 if (!confirm(storageVariant
+
1319 translations
[": unfinished computer game will be erased"]))
1324 else if (score
== "*")
1325 return this.continueGame("computer");
1328 this.vr
= new VariantRules(fen
, []);
1330 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
1333 this.fenStart
= V
.ParseFen(fen
).position
; //this is enough
1337 this.gameId
= getRandString();
1339 this.oppConnected
= true;
1340 this.mycolor
= color
;
1342 if (this.sound
>= 1)
1343 new Audio("/sounds/newgame.mp3").play().catch(err
=> {});
1344 document
.getElementById("modal-newgame").checked
= false;
1345 this.setStorage(); //in case of interruptions
1347 else if (mode
== "computer")
1349 this.compWorker
.postMessage(["init",this.vr
.getFen()]);
1350 this.mycolor
= (Math
.random() < 0.5 ? 'w' : 'b');
1351 this.setStorage(); //store game state
1352 if (this.mycolor
!= this.vr
.turn
)
1353 this.playComputerMove();
1355 //else: against a (IRL) friend or problem solving: nothing more to do
1357 continueGame: function(mode
) {
1359 this.oppid
= (mode
=="human" ? localStorage
.getItem("oppid") : undefined);
1360 const prefix
= (mode
=="computer" ? "comp-" : "");
1361 this.mycolor
= localStorage
.getItem(prefix
+"mycolor");
1362 const moves
= JSON
.parse(localStorage
.getItem(prefix
+"moves"));
1363 const fen
= localStorage
.getItem(prefix
+"fen");
1364 const score
= localStorage
.getItem(prefix
+"score"); //set in "endGame()"
1365 this.fenStart
= localStorage
.getItem(prefix
+"fenStart");
1366 this.vr
= new VariantRules(fen
, moves
);
1367 if (mode
== "human")
1369 this.gameId
= localStorage
.getItem("gameId");
1370 // Send ping to server (answer pong if opponent is connected)
1371 this.conn
.send(JSON
.stringify({
1372 code:"ping",oppid:this.oppid
,gameId:this.gameId
}));
1376 this.compWorker
.postMessage(["init",fen
]);
1377 if (this.mycolor
!= this.vr
.turn
)
1378 this.playComputerMove();
1380 if (moves
.length
> 0)
1382 const lastMove
= moves
[moves
.length
-1];
1383 this.vr
.undo(lastMove
);
1384 this.incheck
= this.vr
.getCheckSquares(lastMove
);
1385 this.vr
.play(lastMove
, "ingame");
1389 // Small delay required when continuation run faster than drawing page
1390 setTimeout(() => this.endGame(score
), 100);
1393 playComputerMove: function() {
1394 this.timeStart
= Date
.now();
1395 this.compWorker
.postMessage(["askmove"]);
1397 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1398 getSquareId: function(o
) {
1399 // NOTE: a separator is required to allow any size of board
1400 return "sq-" + o
.x
+ "-" + o
.y
;
1403 getSquareFromId: function(id
) {
1404 let idParts
= id
.split('-');
1405 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
1407 mousedown: function(e
) {
1408 e
= e
|| window
.event
;
1410 let elem
= e
.target
;
1411 while (!ingame
&& elem
!== null)
1413 if (elem
.classList
.contains("game"))
1418 elem
= elem
.parentElement
;
1420 if (!ingame
) //let default behavior (click on button...)
1422 e
.preventDefault(); //disable native drag & drop
1423 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
1425 // Next few lines to center the piece on mouse cursor
1426 let rect
= e
.target
.parentNode
.getBoundingClientRect();
1428 x: rect
.x
+ rect
.width
/2,
1429 y: rect
.y
+ rect
.width
/2,
1430 id: e
.target
.parentNode
.id
1432 this.selectedPiece
= e
.target
.cloneNode();
1433 this.selectedPiece
.style
.position
= "absolute";
1434 this.selectedPiece
.style
.top
= 0;
1435 this.selectedPiece
.style
.display
= "inline-block";
1436 this.selectedPiece
.style
.zIndex
= 3000;
1437 const startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1438 this.possibleMoves
= [];
1439 if (!["idle","chat"].includes(this.mode
))
1441 const color
= ["friend","problem"].includes(this.mode
)
1444 if (this.vr
.canIplay(color
,startSquare
))
1445 this.possibleMoves
= this.vr
.getPossibleMovesFrom(startSquare
);
1447 // Next line add moving piece just after current image
1448 // (required for Crazyhouse reserve)
1449 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1452 mousemove: function(e
) {
1453 if (!this.selectedPiece
)
1455 e
= e
|| window
.event
;
1456 // If there is an active element, move it around
1457 if (!!this.selectedPiece
)
1459 const [offsetX
,offsetY
] = !!e
.clientX
1460 ? [e
.clientX
,e
.clientY
] //desktop browser
1461 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1462 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1463 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1466 mouseup: function(e
) {
1467 if (!this.selectedPiece
)
1469 e
= e
|| window
.event
;
1470 // Read drop target (or parentElement, parentNode... if type == "img")
1471 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1472 const [offsetX
,offsetY
] = !!e
.clientX
1473 ? [e
.clientX
,e
.clientY
]
1474 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1475 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1476 this.selectedPiece
.style
.zIndex
= 3000;
1477 // Next condition: classList.contains(piece) fails because of marks
1478 while (landing
.tagName
== "IMG")
1479 landing
= landing
.parentNode
;
1480 if (this.start
.id
== landing
.id
)
1482 // A click: selectedPiece and possibleMoves are already filled
1485 // OK: process move attempt
1486 let endSquare
= this.getSquareFromId(landing
.id
);
1487 let moves
= this.findMatchingMoves(endSquare
);
1488 this.possibleMoves
= [];
1489 if (moves
.length
> 1)
1490 this.choices
= moves
;
1491 else if (moves
.length
==1)
1492 this.play(moves
[0]);
1493 // Else: impossible move
1494 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1495 delete this.selectedPiece
;
1496 this.selectedPiece
= null;
1498 findMatchingMoves: function(endSquare
) {
1499 // Run through moves list and return the matching set (if promotions...)
1501 this.possibleMoves
.forEach(function(m
) {
1502 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1507 animateMove: function(move) {
1508 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1509 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1510 let rectStart
= startSquare
.getBoundingClientRect();
1511 let rectEnd
= endSquare
.getBoundingClientRect();
1512 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1514 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1515 // HACK for animation (with positive translate, image slides "under background")
1516 // Possible improvement: just alter squares on the piece's way...
1517 squares
= document
.getElementsByClassName("board");
1518 for (let i
=0; i
<squares
.length
; i
++)
1520 let square
= squares
.item(i
);
1521 if (square
.id
!= this.getSquareId(move.start
))
1522 square
.style
.zIndex
= "-1";
1524 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1525 translation
.y
+ "px)";
1526 movingPiece
.style
.transitionDuration
= "0.2s";
1527 movingPiece
.style
.zIndex
= "3000";
1529 for (let i
=0; i
<squares
.length
; i
++)
1530 squares
.item(i
).style
.zIndex
= "auto";
1531 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1535 play: function(move, programmatic
) {
1538 // Navigate after game is over
1539 if (this.cursor
>= this.vr
.moves
.length
)
1540 return; //already at the end
1541 move = this.vr
.moves
[this.cursor
++];
1543 if (!!programmatic
) //computer or human opponent
1545 this.animateMove(move);
1548 // Not programmatic, or animation is over
1549 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1550 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1551 if (!["idle","chat"].includes(this.mode
))
1553 // Emergency check, if human game started "at the same time"
1554 // TODO: robustify this...
1555 if (this.mode
== "human" && !!move.computer
)
1557 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1558 this.vr
.play(move, "ingame");
1559 if (this.sound
== 2)
1560 new Audio("/sounds/move.mp3").play().catch(err
=> {});
1561 if (this.mode
== "computer")
1563 // Send the move to web worker (TODO: including his own moves?!)
1564 this.compWorker
.postMessage(["newmove",move]);
1569 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1570 this.$forceUpdate(); //TODO: ?!
1572 if (!["idle","chat"].includes(this.mode
))
1574 const eog
= this.vr
.checkGameOver();
1577 if (["human","computer"].includes(this.mode
))
1581 // Just show score on screen (allow undo)
1583 this.showScoreMsg();
1587 if (["human","computer"].includes(this.mode
))
1588 this.updateStorage(); //after our moves and opponent moves
1589 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
&& this.score
== "*")
1590 this.playComputerMove();
1593 // Navigate after game is over
1594 if (this.cursor
== 0)
1595 return; //already at the beginning
1596 if (this.cursor
== this.vr
.moves
.length
)
1597 this.incheck
= []; //in case of...
1598 const move = this.vr
.moves
[--this.cursor
];
1599 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1600 this.$forceUpdate(); //TODO: ?!
1602 undoInGame: function() {
1603 const lm
= this.vr
.lastMove
;
1607 if (this.sound
== 2)
1608 new Audio("/sounds/undo.mp3").play().catch(err
=> {});
1609 const lmBefore
= this.vr
.lastMove
;
1612 this.vr
.undo(lmBefore
);
1613 this.incheck
= this.vr
.getCheckSquares(lmBefore
);
1614 this.vr
.play(lmBefore
, "ingame");