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 online game'] },
60 "playing": this.mode
== "human",
64 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
66 if (["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 (["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
)
309 'ghost': !!this.selectedPiece
310 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
313 src: "/images/pieces/" +
314 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
320 if (this.hints
&& hintSquares
[ci
][cj
])
330 src: "/images/mark.svg",
341 ['board'+sizeY
]: true,
342 'light-square': (i
+j
)%2==0,
343 'dark-square': (i
+j
)%2==1,
345 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
346 'incheck': showLight
&& incheckSq
[ci
][cj
],
349 id: this.getSquareId({x:ci
,y:cj
}),
358 if (!["idle","chat"].includes(this.mode
))
363 on: { click: this.resign
},
364 attrs: { "aria-label": translations
['Resign'] },
370 [h('i', { 'class': { "material-icons": true } }, "flag")])
373 else if (this.vr
.moves
.length
> 0)
375 // A game finished, and another is not started yet: allow navigation
376 actionArray
= actionArray
.concat([
379 on: { click: e
=> this.undo() },
380 attrs: { "aria-label": translations
['Undo'] },
386 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
389 on: { click: e
=> this.play() },
390 attrs: { "aria-label": translations
['Play'] },
396 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
400 if (["friend","problem"].includes(this.mode
))
402 actionArray
= actionArray
.concat(
406 on: { click: this.undoInGame
},
407 attrs: { "aria-label": translations
['Undo'] },
413 [h('i', { 'class': { "material-icons": true } }, "undo")]
417 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
418 attrs: { "aria-label": translations
['Flip'] },
424 [h('i', { 'class': { "material-icons": true } }, "cached")]
428 elementArray
.push(gameDiv
);
429 if (!!this.vr
.reserve
)
431 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
432 let myReservePiecesArray
= [];
433 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
435 myReservePiecesArray
.push(h('div',
437 'class': {'board':true, ['board'+sizeY
+'-reserve']:true},
438 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
443 'class': {"piece":true, "reserve":true},
445 "src": "/images/pieces/" +
446 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
450 {"class": { "reserve-count": true } },
451 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
455 let oppReservePiecesArray
= [];
456 const oppCol
= this.vr
.getOppCol(this.mycolor
);
457 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
459 oppReservePiecesArray
.push(h('div',
461 'class': {'board':true, ['board'+sizeY
+'-reserve']:true},
462 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
467 'class': {"piece":true, "reserve":true},
469 "src": "/images/pieces/" +
470 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
474 {"class": { "reserve-count": true } },
475 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
479 let reserves
= h('div',
491 "reserve-row-1": true,
497 { 'class': { 'row': true }},
498 oppReservePiecesArray
502 elementArray
.push(reserves
);
507 attrs: { "id": "modal-eog", type: "checkbox" },
508 "class": { "modal": true },
512 attrs: { "role": "dialog", "aria-labelledby": "eogMessage" },
527 attrs: { "for": "modal-eog" },
528 "class": { "modal-close": true },
533 attrs: { "id": "eogMessage" },
534 "class": { "section": true },
535 domProps: { innerHTML: this.endgameMessage
},
543 elementArray
= elementArray
.concat(modalEog
);
545 const modalFenEdit
= [
548 attrs: { "id": "modal-fenedit", type: "checkbox" },
549 "class": { "modal": true },
553 attrs: { "role": "dialog", "aria-labelledby": "titleFenedit" },
558 "class": { "card": true, "smallpad": true },
563 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
564 "class": { "modal-close": true },
569 attrs: { "id": "titleFenedit" },
570 "class": { "section": true },
571 domProps: { innerHTML: translations
["Position + flags (FEN):"] },
579 value: VariantRules
.GenRandInitFen(),
587 const fen
= document
.getElementById("input-fen").value
;
588 document
.getElementById("modal-fenedit").checked
= false;
589 this.newGame("friend", fen
);
592 domProps: { innerHTML: translations
["Ok"] },
599 document
.getElementById("input-fen").value
=
600 VariantRules
.GenRandInitFen();
603 domProps: { innerHTML: translations
["Random"] },
611 elementArray
= elementArray
.concat(modalFenEdit
);
612 const modalSettings
= [
615 attrs: { "id": "modal-settings", type: "checkbox" },
616 "class": { "modal": true },
620 attrs: { "role": "dialog", "aria-labelledby": "settingsTitle" },
625 "class": { "card": true, "smallpad": true },
630 attrs: { "id": "close-settings", "for": "modal-settings" },
631 "class": { "modal-close": true },
636 attrs: { "id": "settingsTitle" },
637 "class": { "section": true },
638 domProps: { innerHTML: translations
["Preferences"] },
646 attrs: { for: "nameSetter" },
647 domProps: { innerHTML: translations
["My name is..."] },
657 on: { "change": this.setMyname
},
667 attrs: { for: "setHints" },
668 domProps: { innerHTML: translations
["Show hints?"] },
678 on: { "change": this.toggleHints
},
688 attrs: { for: "selectColor" },
689 domProps: { innerHTML: translations
["Board colors"] },
694 attrs: { "id": "selectColor" },
695 on: { "change": this.setColor
},
702 innerHTML: translations
["brown"]
704 attrs: { "selected": this.color
=="lichess" },
711 innerHTML: translations
["green"]
713 attrs: { "selected": this.color
=="chesscom" },
719 "value": "chesstempo",
720 innerHTML: translations
["blue"]
722 attrs: { "selected": this.color
=="chesstempo" },
734 attrs: { for: "selectSound" },
735 domProps: { innerHTML: translations
["Play sounds?"] },
740 attrs: { "id": "selectSound" },
741 on: { "change": this.setSound
},
748 innerHTML: translations
["None"]
750 attrs: { "selected": this.sound
==0 },
757 innerHTML: translations
["New game"]
759 attrs: { "selected": this.sound
==1 },
766 innerHTML: translations
["All"]
768 attrs: { "selected": this.sound
==2 },
780 elementArray
= elementArray
.concat(modalSettings
);
785 attrs: { "id": "close-chat", "for": "modal-chat" },
786 "class": { "modal-close": true },
791 attrs: { "id": "titleChat" },
792 "class": { "section": true },
793 domProps: { innerHTML: translations
["Chat with "] + this.oppName
},
797 for (let chat
of this.chats
)
803 "my-chatmsg": chat
.author
==this.myid
,
804 "opp-chatmsg": chat
.author
==this.oppid
,
806 domProps: { innerHTML: chat
.msg
}
811 chatEltsArray
= chatEltsArray
.concat([
817 placeholder: translations
["Type here"],
819 on: { keyup: this.trySendChat
}, //if key is 'enter'
824 attrs: { id: "sendChatBtn"},
825 on: { click: this.sendChat
},
826 domProps: { innerHTML: translations
["Send"] },
833 attrs: { "id": "modal-chat", type: "checkbox" },
834 "class": { "modal": true },
838 attrs: { "role": "dialog", "aria-labelledby": "titleChat" },
843 "class": { "card": true, "smallpad": true },
850 elementArray
= elementArray
.concat(modalChat
);
851 const actions
= h('div',
853 attrs: { "id": "actions" },
854 'class': { 'text-center': true },
858 elementArray
.push(actions
);
859 if (this.score
!= "*" && this.pgnTxt
.length
> 0)
864 attrs: { id: "pgn-div" },
865 "class": { "section-content": true },
878 attrs: { id: "pgn-game" },
879 domProps: { innerHTML: this.pgnTxt
}
884 attrs: { "id": "downloadBtn" },
885 on: { click: this.download
},
886 domProps: { innerHTML: translations
["Download game"] },
893 else if (this.mode
!= "idle")
895 if (this.mode
== "problem")
897 // Show problem solution (on click)
901 attrs: { id: "solution-div" },
902 "class": { "section-content": true },
907 "class": { clickable: true },
908 domProps: { innerHTML: translations
["Show solution"] },
909 on: { click: this.toggleShowSolution
},
914 attrs: { id: "problem-solution" },
915 domProps: { innerHTML: this.problem
.solution
}
926 attrs: { id: "fen-div" },
927 "class": { "section-content": true },
932 attrs: { id: "fen-string" },
933 domProps: { innerHTML: this.vr
.getBaseFen() },
934 "class": { "text-center": true },
947 "col-md-offset-1":true,
949 "col-lg-offset-2":true,
951 // NOTE: click = mousedown + mouseup
953 mousedown: this.mousedown
,
954 mousemove: this.mousemove
,
955 mouseup: this.mouseup
,
956 touchstart: this.mousedown
,
957 touchmove: this.mousemove
,
958 touchend: this.mouseup
,
965 endgameMessage: function() {
966 let eogMessage
= "Unfinished";
970 eogMessage
= translations
["White win"];
973 eogMessage
= translations
["Black win"];
976 eogMessage
= translations
["Draw"];
982 created: function() {
983 const url
= socketUrl
;
984 const humanContinuation
= (localStorage
.getItem("variant") === variant
);
985 const computerContinuation
= (localStorage
.getItem("comp-variant") === variant
);
986 this.myid
= (humanContinuation
? localStorage
.getItem("myid") : getRandString());
987 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
988 const socketOpenListener
= () => {
989 if (humanContinuation
) //game VS human has priority
990 this.continueGame("human");
991 else if (computerContinuation
)
992 this.continueGame("computer");
994 const socketMessageListener
= msg
=> {
995 const data
= JSON
.parse(msg
.data
);
996 const L
= (!!this.vr
? this.vr
.moves
.length : 0);
1000 // Receive opponent's name
1001 this.oppName
= data
.name
;
1005 this.chats
.push({msg:data
.msg
, author:this.oppid
});
1008 // We opened another tab on the same game
1012 "Already playing a game in this variant on another tab!"]);
1014 case "newgame": //opponent found
1015 // oppid: opponent socket ID
1016 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
1018 case "newmove": //..he played!
1019 this.play(data
.move, "animate");
1021 case "pong": //received if we sent a ping (game still alive on our side)
1022 if (this.gameId
!= data
.gameId
)
1023 break; //games IDs don't match: definitely over...
1024 this.oppConnected
= true;
1025 // Send our "last state" informations to opponent
1026 this.conn
.send(JSON
.stringify({
1029 gameId: this.gameId
,
1030 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
1034 case "lastate": //got opponent infos about last move
1035 if (this.gameId
!= data
.gameId
)
1036 break; //games IDs don't match: nothing we can do...
1037 // OK, opponent still in game (which might be over)
1038 if (this.mode
!= "human")
1040 // We finished the game (any result possible)
1041 this.conn
.send(JSON
.stringify({
1044 gameId: this.gameId
,
1048 else if (!!data
.score
) //opponent finished the game
1049 this.endGame(data
.score
);
1050 else if (data
.movesCount
< L
)
1052 // We must tell last move to opponent
1053 this.conn
.send(JSON
.stringify({
1056 lastMove: this.vr
.moves
[L
-1],
1060 else if (data
.movesCount
> L
) //just got last move from him
1061 this.play(data
.lastMove
, "animate");
1063 case "resign": //..you won!
1064 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
1066 // TODO: also use (dis)connect info to count online players?
1069 if (["human","chat"].includes(this.mode
) && this.oppid
== data
.id
)
1070 this.oppConnected
= (data
.code
== "connect");
1071 if (this.oppConnected
&& this.mode
== "chat")
1073 // Send our name to the opponent, in case of he hasn't it
1074 this.conn
.send(JSON
.stringify({
1075 code:"myname", name:this.myname
, oppid: this.oppid
}));
1080 const socketCloseListener
= () => {
1081 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
1082 this.conn
.addEventListener('open', socketOpenListener
);
1083 this.conn
.addEventListener('message', socketMessageListener
);
1084 this.conn
.addEventListener('close', socketCloseListener
);
1086 this.conn
.onopen
= socketOpenListener
;
1087 this.conn
.onmessage
= socketMessageListener
;
1088 this.conn
.onclose
= socketCloseListener
;
1089 // Listen to keyboard left/right to navigate in game
1090 document
.onkeydown
= event
=> {
1091 if (["idle","chat"].includes(this.mode
) &&
1092 !!this.vr
&& this.vr
.moves
.length
> 0 && [37,39].includes(event
.keyCode
))
1094 event
.preventDefault();
1095 if (event
.keyCode
== 37) //Back
1101 // Computer moves web worker logic:
1102 this.compWorker
.postMessage(["scripts",variant
]);
1104 this.compWorker
.onmessage = function(e
) {
1105 let compMove
= e
.data
;
1106 compMove
.computer
= true; //TODO: imperfect attempt to avoid ghost move
1107 // (first move) HACK: small delay to avoid selecting elements
1108 // before they appear on page:
1109 const delay
= Math
.max(500-(Date
.now()-self
.timeStart
), 0);
1111 if (self
.mode
== "computer") //warning: mode could have changed!
1112 self
.play(compMove
, "animate")
1117 setMyname: function(e
) {
1118 this.myname
= e
.target
.value
;
1119 localStorage
["username"] = this.myname
;
1121 trySendChat: function(e
) {
1122 if (e
.keyCode
== 13) //'enter' key
1125 sendChat: function() {
1126 let chatInput
= document
.getElementById("input-chat");
1127 const chatTxt
= chatInput
.value
;
1128 chatInput
.value
= "";
1129 this.chats
.push({msg:chatTxt
, author:this.myid
});
1130 this.conn
.send(JSON
.stringify({
1131 code:"newchat", oppid: this.oppid
, msg: chatTxt
}));
1133 toggleShowSolution: function() {
1134 let problemSolution
= document
.getElementById("problem-solution");
1135 problemSolution
.style
.display
=
1136 !problemSolution
.style
.display
|| problemSolution
.style
.display
== "none"
1140 download: function() {
1141 let content
= document
.getElementById("pgn-game").innerHTML
;
1142 content
= content
.replace(/<br>/g, "\n");
1143 // Prepare and trigger download link
1144 let downloadAnchor
= document
.getElementById("download");
1145 downloadAnchor
.setAttribute("download", "game.pgn");
1146 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
1147 encodeURIComponent(content
);
1148 downloadAnchor
.click();
1150 showScoreMsg: function() {
1151 let modalBox
= document
.getElementById("modal-eog");
1152 modalBox
.checked
= true;
1153 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1155 endGame: function(score
) {
1157 if (["human","computer"].includes(this.mode
))
1159 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1160 localStorage
.setItem(prefix
+"score", score
);
1162 this.showScoreMsg();
1163 // Variants may have special PGN structure (so next function isn't defined here)
1164 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
1165 if (this.mode
== "human" && this.oppConnected
)
1167 // Send our nickname to opponent
1168 this.conn
.send(JSON
.stringify({
1169 code:"myname", name:this.myname
, oppid:this.oppid
}));
1171 this.mode
= (this.mode
=="human" ? "chat" : "idle");
1172 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
1174 setStorage: function() {
1175 if (this.mode
=="human")
1177 localStorage
.setItem("myid", this.myid
);
1178 localStorage
.setItem("oppid", this.oppid
);
1179 localStorage
.setItem("gameId", this.gameId
);
1181 // 'prefix' = "comp-" to resume games vs. computer
1182 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1183 localStorage
.setItem(prefix
+"variant", variant
);
1184 localStorage
.setItem(prefix
+"mycolor", this.mycolor
);
1185 localStorage
.setItem(prefix
+"fenStart", this.fenStart
);
1186 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1187 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1188 localStorage
.setItem(prefix
+"score", "*");
1190 updateStorage: function() {
1191 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1192 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1193 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1194 if (this.score
!= "*")
1195 localStorage
.setItem(prefix
+"score", this.score
);
1197 // "computer mode" clearing is done through the menu
1198 clearStorage: function() {
1199 if (["human","chat"].includes(this.mode
))
1201 delete localStorage
["myid"];
1202 delete localStorage
["oppid"];
1203 delete localStorage
["gameId"];
1205 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1206 delete localStorage
[prefix
+"variant"];
1207 delete localStorage
[prefix
+"mycolor"];
1208 delete localStorage
[prefix
+"fenStart"];
1209 delete localStorage
[prefix
+"moves"];
1210 delete localStorage
[prefix
+"fen"];
1211 delete localStorage
[prefix
+"score"];
1213 // HACK because mini-css tooltips are persistent after click...
1214 getRidOfTooltip: function(elt
) {
1215 elt
.style
.visibility
= "hidden";
1216 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
1218 startChat: function(e
) {
1219 this.getRidOfTooltip(e
.currentTarget
);
1220 document
.getElementById("modal-chat").checked
= true;
1222 clearComputerGame: function(e
) {
1223 this.getRidOfTooltip(e
.currentTarget
);
1224 this.clearStorage(); //this.mode=="computer" (already checked)
1225 location
.reload(); //to see clearing effects
1227 showSettings: function(e
) {
1228 this.getRidOfTooltip(e
.currentTarget
);
1229 document
.getElementById("modal-settings").checked
= true;
1231 toggleHints: function() {
1232 this.hints
= !this.hints
;
1233 localStorage
["hints"] = (this.hints
? "1" : "0");
1235 setColor: function(e
) {
1236 this.color
= e
.target
.options
[e
.target
.selectedIndex
].value
;
1237 localStorage
["color"] = this.color
;
1239 setSound: function(e
) {
1240 this.sound
= parseInt(e
.target
.options
[e
.target
.selectedIndex
].value
);
1241 localStorage
["sound"] = this.sound
;
1243 clickGameSeek: function(e
) {
1244 this.getRidOfTooltip(e
.currentTarget
);
1245 if (this.mode
== "human")
1246 return; //no newgame while playing
1249 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
1253 this.newGame("human");
1255 clickComputerGame: function(e
) {
1256 this.getRidOfTooltip(e
.currentTarget
);
1257 this.newGame("computer");
1259 clickFriendGame: function(e
) {
1260 this.getRidOfTooltip(e
.currentTarget
);
1261 document
.getElementById("modal-fenedit").checked
= true;
1263 resign: function(e
) {
1264 this.getRidOfTooltip(e
.currentTarget
);
1265 if (this.mode
== "human" && this.oppConnected
)
1268 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
1269 } catch (INVALID_STATE_ERR
) {
1270 return; //socket is not ready (and not yet reconnected)
1273 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
1275 newGame: function(mode
, fenInit
, color
, oppId
) {
1276 let fen
= fenInit
|| VariantRules
.GenRandInitFen();
1277 console
.log(fen
); //DEBUG
1278 if (mode
=="human" && !oppId
)
1280 const storageVariant
= localStorage
.getItem("variant");
1281 if (!!storageVariant
&& storageVariant
!== variant
)
1283 return alert(translations
["Finish your "] +
1284 storageVariant
+ translations
[" game first!"]);
1286 // Send game request and wait..
1288 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
1289 } catch (INVALID_STATE_ERR
) {
1290 return; //nothing achieved
1293 let modalBox
= document
.getElementById("modal-newgame");
1294 modalBox
.checked
= true;
1295 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1298 if (["human","chat"].includes(this.mode
))
1300 // Start a new game vs. another human (or...) => forget about current one
1301 this.clearStorage();
1303 if (mode
== "computer")
1305 const storageVariant
= localStorage
.getItem("comp-variant");
1306 if (!!storageVariant
)
1308 const score
= localStorage
.getItem("comp-score");
1309 if (storageVariant
!== variant
&& score
== "*")
1311 if (!confirm(storageVariant
+
1312 translations
[": unfinished computer game will be erased"]))
1317 else if (score
== "*")
1318 return this.continueGame("computer");
1321 this.vr
= new VariantRules(fen
, []);
1323 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
1326 this.fenStart
= V
.ParseFen(fen
).position
; //this is enough
1330 this.gameId
= getRandString();
1332 this.oppConnected
= true;
1333 this.mycolor
= color
;
1335 if (this.sound
>= 1)
1336 new Audio("/sounds/newgame.mp3").play().catch(err
=> {});
1337 document
.getElementById("modal-newgame").checked
= false;
1338 this.setStorage(); //in case of interruptions
1340 else if (mode
== "computer")
1342 this.compWorker
.postMessage(["init",this.vr
.getFen()]);
1343 this.mycolor
= (Math
.random() < 0.5 ? 'w' : 'b');
1344 this.setStorage(); //store game state
1345 if (this.mycolor
!= this.vr
.turn
)
1346 this.playComputerMove();
1348 //else: against a (IRL) friend or problem solving: nothing more to do
1350 continueGame: function(mode
) {
1352 this.oppid
= (mode
=="human" ? localStorage
.getItem("oppid") : undefined);
1353 const prefix
= (mode
=="computer" ? "comp-" : "");
1354 this.mycolor
= localStorage
.getItem(prefix
+"mycolor");
1355 const moves
= JSON
.parse(localStorage
.getItem(prefix
+"moves"));
1356 const fen
= localStorage
.getItem(prefix
+"fen");
1357 const score
= localStorage
.getItem(prefix
+"score"); //set in "endGame()"
1358 this.fenStart
= localStorage
.getItem(prefix
+"fenStart");
1359 this.vr
= new VariantRules(fen
, moves
);
1360 if (mode
== "human")
1362 this.gameId
= localStorage
.getItem("gameId");
1363 // Send ping to server (answer pong if opponent is connected)
1364 this.conn
.send(JSON
.stringify({
1365 code:"ping",oppid:this.oppid
,gameId:this.gameId
}));
1369 this.compWorker
.postMessage(["init",fen
]);
1370 if (this.mycolor
!= this.vr
.turn
)
1371 this.playComputerMove();
1373 if (moves
.length
> 0)
1375 const lastMove
= moves
[moves
.length
-1];
1376 this.vr
.undo(lastMove
);
1377 this.incheck
= this.vr
.getCheckSquares(lastMove
);
1378 this.vr
.play(lastMove
, "ingame");
1382 // Small delay required when continuation run faster than drawing page
1383 setTimeout(() => this.endGame(score
), 100);
1386 playComputerMove: function() {
1387 this.timeStart
= Date
.now();
1388 this.compWorker
.postMessage(["askmove"]);
1390 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1391 getSquareId: function(o
) {
1392 // NOTE: a separator is required to allow any size of board
1393 return "sq-" + o
.x
+ "-" + o
.y
;
1396 getSquareFromId: function(id
) {
1397 let idParts
= id
.split('-');
1398 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
1400 mousedown: function(e
) {
1401 e
= e
|| window
.event
;
1403 let elem
= e
.target
;
1404 while (!ingame
&& elem
!== null)
1406 if (elem
.classList
.contains("game"))
1411 elem
= elem
.parentElement
;
1413 if (!ingame
) //let default behavior (click on button...)
1415 e
.preventDefault(); //disable native drag & drop
1416 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
1418 // Next few lines to center the piece on mouse cursor
1419 let rect
= e
.target
.parentNode
.getBoundingClientRect();
1421 x: rect
.x
+ rect
.width
/2,
1422 y: rect
.y
+ rect
.width
/2,
1423 id: e
.target
.parentNode
.id
1425 this.selectedPiece
= e
.target
.cloneNode();
1426 this.selectedPiece
.style
.position
= "absolute";
1427 this.selectedPiece
.style
.top
= 0;
1428 this.selectedPiece
.style
.display
= "inline-block";
1429 this.selectedPiece
.style
.zIndex
= 3000;
1430 const startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1431 this.possibleMoves
= [];
1432 if (!["idle","chat"].includes(this.mode
))
1434 const color
= ["friend","problem"].includes(this.mode
)
1437 if (this.vr
.canIplay(color
,startSquare
))
1438 this.possibleMoves
= this.vr
.getPossibleMovesFrom(startSquare
);
1440 // Next line add moving piece just after current image
1441 // (required for Crazyhouse reserve)
1442 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1445 mousemove: function(e
) {
1446 if (!this.selectedPiece
)
1448 e
= e
|| window
.event
;
1449 // If there is an active element, move it around
1450 if (!!this.selectedPiece
)
1452 const [offsetX
,offsetY
] = !!e
.clientX
1453 ? [e
.clientX
,e
.clientY
] //desktop browser
1454 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1455 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1456 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1459 mouseup: function(e
) {
1460 if (!this.selectedPiece
)
1462 e
= e
|| window
.event
;
1463 // Read drop target (or parentElement, parentNode... if type == "img")
1464 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1465 const [offsetX
,offsetY
] = !!e
.clientX
1466 ? [e
.clientX
,e
.clientY
]
1467 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1468 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1469 this.selectedPiece
.style
.zIndex
= 3000;
1470 // Next condition: classList.contains(piece) fails because of marks
1471 while (landing
.tagName
== "IMG")
1472 landing
= landing
.parentNode
;
1473 if (this.start
.id
== landing
.id
)
1475 // A click: selectedPiece and possibleMoves are already filled
1478 // OK: process move attempt
1479 let endSquare
= this.getSquareFromId(landing
.id
);
1480 let moves
= this.findMatchingMoves(endSquare
);
1481 this.possibleMoves
= [];
1482 if (moves
.length
> 1)
1483 this.choices
= moves
;
1484 else if (moves
.length
==1)
1485 this.play(moves
[0]);
1486 // Else: impossible move
1487 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1488 delete this.selectedPiece
;
1489 this.selectedPiece
= null;
1491 findMatchingMoves: function(endSquare
) {
1492 // Run through moves list and return the matching set (if promotions...)
1494 this.possibleMoves
.forEach(function(m
) {
1495 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1500 animateMove: function(move) {
1501 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1502 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1503 let rectStart
= startSquare
.getBoundingClientRect();
1504 let rectEnd
= endSquare
.getBoundingClientRect();
1505 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1507 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1508 // HACK for animation (with positive translate, image slides "under background")
1509 // Possible improvement: just alter squares on the piece's way...
1510 squares
= document
.getElementsByClassName("board");
1511 for (let i
=0; i
<squares
.length
; i
++)
1513 let square
= squares
.item(i
);
1514 if (square
.id
!= this.getSquareId(move.start
))
1515 square
.style
.zIndex
= "-1";
1517 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1518 translation
.y
+ "px)";
1519 movingPiece
.style
.transitionDuration
= "0.2s";
1520 movingPiece
.style
.zIndex
= "3000";
1522 for (let i
=0; i
<squares
.length
; i
++)
1523 squares
.item(i
).style
.zIndex
= "auto";
1524 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1528 play: function(move, programmatic
) {
1531 // Navigate after game is over
1532 if (this.cursor
>= this.vr
.moves
.length
)
1533 return; //already at the end
1534 move = this.vr
.moves
[this.cursor
++];
1536 if (!!programmatic
) //computer or human opponent
1538 this.animateMove(move);
1541 // Not programmatic, or animation is over
1542 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1543 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1544 if (!["idle","chat"].includes(this.mode
))
1546 // Emergency check, if human game started "at the same time"
1547 // TODO: robustify this...
1548 if (this.mode
== "human" && !!move.computer
)
1550 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1551 this.vr
.play(move, "ingame");
1552 if (this.sound
== 2)
1553 new Audio("/sounds/move.mp3").play().catch(err
=> {});
1554 if (this.mode
== "computer")
1556 // Send the move to web worker (TODO: including his own moves?!)
1557 this.compWorker
.postMessage(["newmove",move]);
1562 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1563 this.$forceUpdate(); //TODO: ?!
1565 if (!["idle","chat"].includes(this.mode
))
1567 const eog
= this.vr
.checkGameOver();
1570 if (["human","computer"].includes(this.mode
))
1574 // Just show score on screen (allow undo)
1576 this.showScoreMsg();
1580 if (["human","computer"].includes(this.mode
))
1581 this.updateStorage(); //after our moves and opponent moves
1582 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
&& this.score
== "*")
1583 this.playComputerMove();
1586 // Navigate after game is over
1587 if (this.cursor
== 0)
1588 return; //already at the beginning
1589 if (this.cursor
== this.vr
.moves
.length
)
1590 this.incheck
= []; //in case of...
1591 const move = this.vr
.moves
[--this.cursor
];
1592 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1593 this.$forceUpdate(); //TODO: ?!
1595 undoInGame: function() {
1596 const lm
= this.vr
.lastMove
;
1600 if (this.sound
== 2)
1601 new Audio("/sounds/undo.mp3").play().catch(err
=> {});
1602 const lmBefore
= this.vr
.lastMove
;
1605 this.vr
.undo(lmBefore
);
1606 this.incheck
= this.vr
.getCheckSquares(lmBefore
);
1607 this.vr
.play(lmBefore
, "ingame");