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 const smallScreen
= (window
.innerWidth
<= 420);
44 // Precompute hints squares to facilitate rendering
45 let hintSquares
= doubleArray(sizeX
, sizeY
, false);
46 this.possibleMoves
.forEach(m
=> { hintSquares
[m
.end
.x
][m
.end
.y
] = true; });
47 // Also precompute in-check squares
48 let incheckSq
= doubleArray(sizeX
, sizeY
, false);
49 this.incheck
.forEach(sq
=> { incheckSq
[sq
[0]][sq
[1]] = true; });
50 let elementArray
= [];
55 on: { click: this.clickGameSeek
},
56 attrs: { "aria-label": 'New online game' },
59 "bottom": true, //display below
61 "playing": this.mode
== "human",
65 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
67 if (["idle","chat","computer"].includes(this.mode
))
72 on: { click: this.clickComputerGame
},
73 attrs: { "aria-label": 'New game VS computer' },
77 "playing": this.mode
== "computer",
81 [h('i', { 'class': { "material-icons": true } }, "computer")])
84 if (["idle","chat","friend"].includes(this.mode
))
89 on: { click: this.clickFriendGame
},
90 attrs: { "aria-label": 'New IRL game' },
94 "playing": this.mode
== "friend",
98 [h('i', { 'class': { "material-icons": true } }, "people")])
103 const square00
= document
.getElementById("sq-0-0");
104 const squareWidth
= !!square00
105 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
107 const settingsBtnElt
= document
.getElementById("settingsBtn");
108 const indicWidth
= !!settingsBtnElt
//-2 for border:
109 ? parseFloat(window
.getComputedStyle(settingsBtnElt
).height
.slice(0,-2)) - 2
110 : (smallScreen
? 31 : 37);
111 if (["chat","human"].includes(this.mode
))
113 const connectedIndic
= h(
117 "topindicator": true,
119 "connected": this.oppConnected
,
120 "disconnected": !this.oppConnected
,
123 "width": indicWidth
+ "px",
124 "height": indicWidth
+ "px",
128 elementArray
.push(connectedIndic
);
130 if (this.mode
== "chat")
132 const chatButton
= h(
135 on: { click: this.startChat
},
137 "aria-label": 'Start chat',
142 "topindicator": true,
144 "settings-btn": !smallScreen
,
145 "settings-btn-small": smallScreen
,
148 [h('i', { 'class': { "material-icons": true } }, "chat")]
150 elementArray
.push(chatButton
);
152 else if (this.mode
== "computer")
154 const clearButton
= h(
157 on: { click: this.clearComputerGame
},
159 "aria-label": 'Clear computer game',
164 "topindicator": true,
166 "settings-btn": !smallScreen
,
167 "settings-btn-small": smallScreen
,
170 [h('i', { 'class': { "material-icons": true } }, "clear")]
172 elementArray
.push(clearButton
);
178 "topindicator": true,
180 "white-turn": this.vr
.turn
=="w",
181 "black-turn": this.vr
.turn
=="b",
184 "width": indicWidth
+ "px",
185 "height": indicWidth
+ "px",
189 elementArray
.push(turnIndic
);
190 const settingsBtn
= h(
193 on: { click: this.showSettings
},
195 "aria-label": 'Settings',
200 "topindicator": true,
202 "settings-btn": !smallScreen
,
203 "settings-btn-small": smallScreen
,
206 [h('i', { 'class': { "material-icons": true } }, "settings")]
208 elementArray
.push(settingsBtn
);
209 if (this.mode
== "problem")
211 // Show problem instructions
215 attrs: { id: "instructions-div" },
218 "section-content": true,
224 attrs: { id: "problem-instructions" },
225 domProps: { innerHTML: this.problem
.instructions
}
232 const choices
= h('div',
234 attrs: { "id": "choices" },
235 'class': { 'row': true },
237 "display": this.choices
.length
>0?"block":"none",
238 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
239 "width": (this.choices
.length
* squareWidth
) + "px",
240 "height": squareWidth
+ "px",
243 this.choices
.map( m
=> { //a "choice" is a move
248 ['board'+sizeY
]: true,
251 'width': (100/this.choices
.length
) + "%",
252 'padding-bottom': (100/this.choices
.length
) + "%",
257 attrs: { "src": '/images/pieces/' +
258 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
259 'class': { 'choice-piece': true },
261 "click": e
=> { this.play(m
); this.choices
=[]; },
262 // NOTE: add 'touchstart' event to fix a problem on smartphones
263 "touchstart": e
=> { this.play(m
); this.choices
=[]; },
270 // Create board element (+ reserves if needed by variant or mode)
271 const lm
= this.vr
.lastMove
;
272 const showLight
= this.hints
&&
273 (!["idle","chat"].includes(this.mode
) || this.cursor
==this.vr
.moves
.length
);
274 const gameDiv
= h('div',
276 'class': { 'game': true },
278 [_
.range(sizeX
).map(i
=> {
279 let ci
= (this.mycolor
=='w' ? i : sizeX
-i
-1);
286 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
288 _
.range(sizeY
).map(j
=> {
289 let cj
= (this.mycolor
=='w' ? j : sizeY
-j
-1);
291 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
)
299 'ghost': !!this.selectedPiece
300 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
303 src: "/images/pieces/" +
304 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
310 if (this.hints
&& hintSquares
[ci
][cj
])
320 src: "/images/mark.svg",
331 ['board'+sizeY
]: true,
332 'light-square': (i
+j
)%2==0,
333 'dark-square': (i
+j
)%2==1,
335 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
336 'incheck': showLight
&& incheckSq
[ci
][cj
],
339 id: this.getSquareId({x:ci
,y:cj
}),
348 if (!["idle","chat"].includes(this.mode
))
353 on: { click: this.resign
},
354 attrs: { "aria-label": 'Resign' },
358 "small": smallScreen
,
361 [h('i', { 'class': { "material-icons": true } }, "flag")])
364 else if (this.vr
.moves
.length
> 0)
366 // A game finished, and another is not started yet: allow navigation
367 actionArray
= actionArray
.concat([
370 on: { click: e
=> this.undo() },
371 attrs: { "aria-label": 'Undo' },
373 "small": smallScreen
,
377 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
380 on: { click: e
=> this.play() },
381 attrs: { "aria-label": 'Play' },
382 "class": { "small": smallScreen
},
384 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
388 if (["friend","problem"].includes(this.mode
))
390 actionArray
= actionArray
.concat(
394 on: { click: this.undoInGame
},
395 attrs: { "aria-label": 'Undo' },
397 "small": smallScreen
,
401 [h('i', { 'class': { "material-icons": true } }, "undo")]
405 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
406 attrs: { "aria-label": 'Flip' },
407 "class": { "small": smallScreen
},
409 [h('i', { 'class': { "material-icons": true } }, "cached")]
413 elementArray
.push(gameDiv
);
414 if (!!this.vr
.reserve
)
416 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
417 let myReservePiecesArray
= [];
418 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
420 myReservePiecesArray
.push(h('div',
422 'class': {'board':true, ['board'+sizeY
]:true},
423 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
428 'class': {"piece":true},
430 "src": "/images/pieces/" +
431 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
435 {"class": { "reserve-count": true } },
436 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
440 let oppReservePiecesArray
= [];
441 const oppCol
= this.vr
.getOppCol(this.mycolor
);
442 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
444 oppReservePiecesArray
.push(h('div',
446 'class': {'board':true, ['board'+sizeY
]:true},
447 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
452 'class': {"piece":true},
454 "src": "/images/pieces/" +
455 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
459 {"class": { "reserve-count": true } },
460 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
464 let reserves
= h('div',
476 "reserve-row-1": true,
482 { 'class': { 'row': true }},
483 oppReservePiecesArray
487 elementArray
.push(reserves
);
492 attrs: { "id": "modal-eog", type: "checkbox" },
493 "class": { "modal": true },
497 attrs: { "role": "dialog", "aria-labelledby": "eogMessage" },
502 "class": { "card": true, "smallpad": true },
507 attrs: { "for": "modal-eog" },
508 "class": { "modal-close": true },
513 attrs: { "id": "eogMessage" },
514 "class": { "section": true },
515 domProps: { innerHTML: this.endgameMessage
},
523 elementArray
= elementArray
.concat(modalEog
);
525 const modalFenEdit
= [
528 attrs: { "id": "modal-fenedit", type: "checkbox" },
529 "class": { "modal": true },
533 attrs: { "role": "dialog", "aria-labelledby": "titleFenedit" },
538 "class": { "card": true, "smallpad": true },
543 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
544 "class": { "modal-close": true },
549 attrs: { "id": "titleFenedit" },
550 "class": { "section": true },
551 domProps: { innerHTML: "Position + flags (FEN):" },
559 value: VariantRules
.GenRandInitFen(),
567 const fen
= document
.getElementById("input-fen").value
;
568 document
.getElementById("modal-fenedit").checked
= false;
569 this.newGame("friend", fen
);
572 domProps: { innerHTML: "Ok" },
579 document
.getElementById("input-fen").value
=
580 VariantRules
.GenRandInitFen();
583 domProps: { innerHTML: "Random" },
591 elementArray
= elementArray
.concat(modalFenEdit
);
592 const modalSettings
= [
595 attrs: { "id": "modal-settings", type: "checkbox" },
596 "class": { "modal": true },
600 attrs: { "role": "dialog", "aria-labelledby": "settingsTitle" },
605 "class": { "card": true, "smallpad": true },
610 attrs: { "id": "close-settings", "for": "modal-settings" },
611 "class": { "modal-close": true },
616 attrs: { "id": "settingsTitle" },
617 "class": { "section": true },
618 domProps: { innerHTML: "Preferences" },
626 attrs: { for: "nameSetter" },
627 domProps: { innerHTML: "My name is..." },
637 on: { "change": this.setMyname
},
647 attrs: { for: "setHints" },
648 domProps: { innerHTML: "Show hints?" },
658 on: { "change": this.toggleHints
},
668 attrs: { for: "selectColor" },
669 domProps: { innerHTML: "Board colors" },
674 attrs: { "id": "selectColor" },
675 on: { "change": this.setColor
},
684 attrs: { "selected": this.color
=="lichess" },
693 attrs: { "selected": this.color
=="chesscom" },
699 "value": "chesstempo",
702 attrs: { "selected": this.color
=="chesstempo" },
714 attrs: { for: "selectSound" },
715 domProps: { innerHTML: "Play sounds?" },
720 attrs: { "id": "selectSound" },
721 on: { "change": this.setSound
},
730 attrs: { "selected": this.sound
==0 },
739 attrs: { "selected": this.sound
==1 },
748 attrs: { "selected": this.sound
==2 },
760 elementArray
= elementArray
.concat(modalSettings
);
765 attrs: { "id": "close-chat", "for": "modal-chat" },
766 "class": { "modal-close": true },
771 attrs: { "id": "titleChat" },
772 "class": { "section": true },
773 domProps: { innerHTML: "Chat with " + this.oppName
},
777 for (let chat
of this.chats
)
783 "my-chatmsg": chat
.author
==this.myid
,
784 "opp-chatmsg": chat
.author
==this.oppid
,
786 domProps: { innerHTML: chat
.msg
}
791 chatEltsArray
= chatEltsArray
.concat([
797 placeholder: "Type here",
799 on: { keyup: this.trySendChat
}, //if key is 'enter'
804 on: { click: this.sendChat
},
805 domProps: { innerHTML: "Send" },
812 attrs: { "id": "modal-chat", type: "checkbox" },
813 "class": { "modal": true },
817 attrs: { "role": "dialog", "aria-labelledby": "titleChat" },
822 "class": { "card": true, "smallpad": true },
829 elementArray
= elementArray
.concat(modalChat
);
830 const actions
= h('div',
832 attrs: { "id": "actions" },
833 'class': { 'text-center': true },
837 elementArray
.push(actions
);
838 if (this.score
!= "*" && this.pgnTxt
.length
> 0)
843 attrs: { id: "pgn-div" },
844 "class": { "section-content": true },
857 attrs: { id: "pgn-game" },
858 domProps: { innerHTML: this.pgnTxt
}
863 attrs: { "id": "downloadBtn" },
864 on: { click: this.download
},
865 domProps: { innerHTML: "Download game" },
872 else if (this.mode
!= "idle")
874 if (this.mode
== "problem")
876 // Show problem solution (on click)
880 attrs: { id: "solution-div" },
881 "class": { "section-content": true },
886 domProps: { innerHTML: "Show solution" },
887 on: { click: this.toggleShowSolution
},
892 attrs: { id: "problem-solution" },
893 domProps: { innerHTML: this.problem
.solution
}
904 attrs: { id: "fen-div" },
905 "class": { "section-content": true },
910 attrs: { id: "fen-string" },
911 domProps: { innerHTML: this.vr
.getBaseFen() }
924 "col-md-offset-2":true,
926 "col-lg-offset-3":true,
928 // NOTE: click = mousedown + mouseup
930 mousedown: this.mousedown
,
931 mousemove: this.mousemove
,
932 mouseup: this.mouseup
,
933 touchstart: this.mousedown
,
934 touchmove: this.mousemove
,
935 touchend: this.mouseup
,
942 endgameMessage: function() {
943 let eogMessage
= "Unfinished";
947 eogMessage
= "White win";
950 eogMessage
= "Black win";
959 created: function() {
960 const url
= socketUrl
;
961 const humanContinuation
= (localStorage
.getItem("variant") === variant
);
962 const computerContinuation
= (localStorage
.getItem("comp-variant") === variant
);
963 this.myid
= (humanContinuation
? localStorage
.getItem("myid") : getRandString());
964 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
965 const socketOpenListener
= () => {
966 if (humanContinuation
) //game VS human has priority
967 this.continueGame("human");
968 else if (computerContinuation
)
969 this.continueGame("computer");
971 const socketMessageListener
= msg
=> {
972 const data
= JSON
.parse(msg
.data
);
973 const L
= (!!this.vr
? this.vr
.moves
.length : 0);
977 // Receive opponent's name
978 this.oppName
= data
.name
;
982 this.chats
.push({msg:data
.msg
, author:this.oppid
});
985 // We opened another tab on the same game
988 alert("Already playing a game in this variant on another tab!");
990 case "newgame": //opponent found
991 // oppid: opponent socket ID
992 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
994 case "newmove": //..he played!
995 this.play(data
.move, "animate");
997 case "pong": //received if we sent a ping (game still alive on our side)
998 if (this.gameId
!= data
.gameId
)
999 break; //games IDs don't match: definitely over...
1000 this.oppConnected
= true;
1001 // Send our "last state" informations to opponent
1002 this.conn
.send(JSON
.stringify({
1005 gameId: this.gameId
,
1006 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
1010 case "lastate": //got opponent infos about last move
1011 if (this.gameId
!= data
.gameId
)
1012 break; //games IDs don't match: nothing we can do...
1013 // OK, opponent still in game (which might be over)
1014 if (this.mode
!= "human")
1016 // We finished the game (any result possible)
1017 this.conn
.send(JSON
.stringify({
1020 gameId: this.gameId
,
1024 else if (!!data
.score
) //opponent finished the game
1025 this.endGame(data
.score
);
1026 else if (data
.movesCount
< L
)
1028 // We must tell last move to opponent
1029 this.conn
.send(JSON
.stringify({
1032 lastMove: this.vr
.moves
[L
-1],
1036 else if (data
.movesCount
> L
) //just got last move from him
1037 this.play(data
.lastMove
, "animate");
1039 case "resign": //..you won!
1040 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
1042 // TODO: also use (dis)connect info to count online players?
1045 if (["human","chat"].includes(this.mode
) && this.oppid
== data
.id
)
1046 this.oppConnected
= (data
.code
== "connect");
1047 if (this.oppConnected
&& this.mode
== "chat")
1049 // Send our name to the opponent, in case of he hasn't it
1050 this.conn
.send(JSON
.stringify({
1051 code:"myname", name:this.myname
, oppid: this.oppid
}));
1056 const socketCloseListener
= () => {
1057 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
1058 this.conn
.addEventListener('open', socketOpenListener
);
1059 this.conn
.addEventListener('message', socketMessageListener
);
1060 this.conn
.addEventListener('close', socketCloseListener
);
1062 this.conn
.onopen
= socketOpenListener
;
1063 this.conn
.onmessage
= socketMessageListener
;
1064 this.conn
.onclose
= socketCloseListener
;
1065 // Listen to keyboard left/right to navigate in game
1066 document
.onkeydown
= event
=> {
1067 if (["idle","chat"].includes(this.mode
) &&
1068 !!this.vr
&& this.vr
.moves
.length
> 0 && [37,39].includes(event
.keyCode
))
1070 event
.preventDefault();
1071 if (event
.keyCode
== 37) //Back
1077 // Computer moves web worker logic:
1078 this.compWorker
.postMessage(["scripts",variant
]);
1080 this.compWorker
.onmessage = function(e
) {
1081 let compMove
= e
.data
;
1082 compMove
.computer
= true; //TODO: imperfect attempt to avoid ghost move
1083 // (first move) HACK: small delay to avoid selecting elements
1084 // before they appear on page:
1085 const delay
= Math
.max(500-(Date
.now()-self
.timeStart
), 0);
1087 if (self
.mode
== "computer") //warning: mode could have changed!
1088 self
.play(compMove
, "animate")
1093 setMyname: function(e
) {
1094 this.myname
= e
.target
.value
;
1095 localStorage
["username"] = this.myname
;
1097 trySendChat: function(e
) {
1098 if (e
.keyCode
== 13) //'enter' key
1101 sendChat: function() {
1102 let chatInput
= document
.getElementById("input-chat");
1103 const chatTxt
= chatInput
.value
;
1104 chatInput
.value
= "";
1105 this.chats
.push({msg:chatTxt
, author:this.myid
});
1106 this.conn
.send(JSON
.stringify({
1107 code:"newchat", oppid: this.oppid
, msg: chatTxt
}));
1109 toggleShowSolution: function() {
1110 let problemSolution
= document
.getElementById("problem-solution");
1111 problemSolution
.style
.display
=
1112 !problemSolution
.style
.display
|| problemSolution
.style
.display
== "none"
1116 download: function() {
1117 let content
= document
.getElementById("pgn-game").innerHTML
;
1118 content
= content
.replace(/<br>/g, "\n");
1119 // Prepare and trigger download link
1120 let downloadAnchor
= document
.getElementById("download");
1121 downloadAnchor
.setAttribute("download", "game.pgn");
1122 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
1123 encodeURIComponent(content
);
1124 downloadAnchor
.click();
1126 showScoreMsg: function() {
1127 let modalBox
= document
.getElementById("modal-eog");
1128 modalBox
.checked
= true;
1129 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1131 endGame: function(score
) {
1133 if (["human","computer"].includes(this.mode
))
1135 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1136 localStorage
.setItem(prefix
+"score", score
);
1138 this.showScoreMsg();
1139 // Variants may have special PGN structure (so next function isn't defined here)
1140 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
1141 if (this.mode
== "human" && this.oppConnected
)
1143 // Send our nickname to opponent
1144 this.conn
.send(JSON
.stringify({
1145 code:"myname", name:this.myname
, oppid:this.oppid
}));
1147 this.mode
= (this.mode
=="human" ? "chat" : "idle");
1148 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
1150 setStorage: function() {
1151 if (this.mode
=="human")
1153 localStorage
.setItem("myid", this.myid
);
1154 localStorage
.setItem("oppid", this.oppid
);
1155 localStorage
.setItem("gameId", this.gameId
);
1157 // 'prefix' = "comp-" to resume games vs. computer
1158 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1159 localStorage
.setItem(prefix
+"variant", variant
);
1160 localStorage
.setItem(prefix
+"mycolor", this.mycolor
);
1161 localStorage
.setItem(prefix
+"fenStart", this.fenStart
);
1162 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1163 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1164 localStorage
.setItem(prefix
+"score", "*");
1166 updateStorage: function() {
1167 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1168 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1169 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1170 if (this.score
!= "*")
1171 localStorage
.setItem(prefix
+"score", this.score
);
1173 // "computer mode" clearing is done through the menu
1174 clearStorage: function() {
1175 if (["human","chat"].includes(this.mode
))
1177 delete localStorage
["myid"];
1178 delete localStorage
["oppid"];
1179 delete localStorage
["gameId"];
1181 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1182 delete localStorage
[prefix
+"variant"];
1183 delete localStorage
[prefix
+"mycolor"];
1184 delete localStorage
[prefix
+"fenStart"];
1185 delete localStorage
[prefix
+"moves"];
1186 delete localStorage
[prefix
+"fen"];
1187 delete localStorage
[prefix
+"score"];
1189 // HACK because mini-css tooltips are persistent after click...
1190 getRidOfTooltip: function(elt
) {
1191 elt
.style
.visibility
= "hidden";
1192 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
1194 startChat: function(e
) {
1195 this.getRidOfTooltip(e
.currentTarget
);
1196 document
.getElementById("modal-chat").checked
= true;
1198 clearComputerGame: function(e
) {
1199 this.getRidOfTooltip(e
.currentTarget
);
1200 this.clearStorage(); //this.mode=="computer" (already checked)
1201 location
.reload(); //to see clearing effects
1203 showSettings: function(e
) {
1204 this.getRidOfTooltip(e
.currentTarget
);
1205 document
.getElementById("modal-settings").checked
= true;
1207 toggleHints: function() {
1208 this.hints
= !this.hints
;
1209 localStorage
["hints"] = (this.hints
? "1" : "0");
1211 setColor: function(e
) {
1212 this.color
= e
.target
.options
[e
.target
.selectedIndex
].value
;
1213 localStorage
["color"] = this.color
;
1215 setSound: function(e
) {
1216 this.sound
= parseInt(e
.target
.options
[e
.target
.selectedIndex
].value
);
1217 localStorage
["sound"] = this.sound
;
1219 clickGameSeek: function(e
) {
1220 this.getRidOfTooltip(e
.currentTarget
);
1221 if (this.mode
== "human")
1222 return; //no newgame while playing
1225 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
1229 this.newGame("human");
1231 clickComputerGame: function(e
) {
1232 this.getRidOfTooltip(e
.currentTarget
);
1233 this.newGame("computer");
1235 clickFriendGame: function(e
) {
1236 this.getRidOfTooltip(e
.currentTarget
);
1237 document
.getElementById("modal-fenedit").checked
= true;
1239 resign: function(e
) {
1240 this.getRidOfTooltip(e
.currentTarget
);
1241 if (this.mode
== "human" && this.oppConnected
)
1244 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
1245 } catch (INVALID_STATE_ERR
) {
1246 return; //socket is not ready (and not yet reconnected)
1249 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
1251 newGame: function(mode
, fenInit
, color
, oppId
) {
1252 let fen
= fenInit
|| VariantRules
.GenRandInitFen();
1253 console
.log(fen
); //DEBUG
1254 if (mode
=="human" && !oppId
)
1256 const storageVariant
= localStorage
.getItem("variant");
1257 if (!!storageVariant
&& storageVariant
!== variant
)
1258 return alert("Finish your " + storageVariant
+ " game first!");
1259 // Send game request and wait..
1261 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
1262 } catch (INVALID_STATE_ERR
) {
1263 return; //nothing achieved
1266 let modalBox
= document
.getElementById("modal-newgame");
1267 modalBox
.checked
= true;
1268 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1271 if (["human","chat"].includes(this.mode
))
1273 // Start a new game vs. another human (or...) => forget about current one
1274 this.clearStorage();
1276 if (mode
== "computer")
1278 const storageVariant
= localStorage
.getItem("comp-variant");
1279 if (!!storageVariant
)
1281 const score
= localStorage
.getItem("comp-score");
1282 if (storageVariant
!== variant
&& score
== "*")
1284 if (!confirm("Unfinished " + storageVariant
+
1285 " computer game will be erased"))
1290 else if (score
== "*")
1291 return this.continueGame("computer");
1294 this.vr
= new VariantRules(fen
, []);
1296 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
1299 this.fenStart
= V
.ParseFen(fen
).position
; //this is enough
1303 this.gameId
= getRandString();
1305 this.oppConnected
= true;
1306 this.mycolor
= color
;
1308 if (this.sound
>= 1)
1309 new Audio("/sounds/newgame.mp3").play().catch(err
=> {});
1310 document
.getElementById("modal-newgame").checked
= false;
1311 this.setStorage(); //in case of interruptions
1313 else if (mode
== "computer")
1315 this.compWorker
.postMessage(["init",this.vr
.getFen()]);
1316 this.mycolor
= (Math
.random() < 0.5 ? 'w' : 'b');
1317 this.setStorage(); //store game state
1318 if (this.mycolor
!= this.vr
.turn
)
1319 this.playComputerMove();
1321 //else: against a (IRL) friend or problem solving: nothing more to do
1323 continueGame: function(mode
) {
1325 this.oppid
= (mode
=="human" ? localStorage
.getItem("oppid") : undefined);
1326 const prefix
= (mode
=="computer" ? "comp-" : "");
1327 this.mycolor
= localStorage
.getItem(prefix
+"mycolor");
1328 const moves
= JSON
.parse(localStorage
.getItem(prefix
+"moves"));
1329 const fen
= localStorage
.getItem(prefix
+"fen");
1330 const score
= localStorage
.getItem(prefix
+"score"); //set in "endGame()"
1331 this.fenStart
= localStorage
.getItem(prefix
+"fenStart");
1332 if (mode
== "human")
1334 this.gameId
= localStorage
.getItem("gameId");
1335 // Send ping to server (answer pong if opponent is connected)
1336 this.conn
.send(JSON
.stringify({
1337 code:"ping",oppid:this.oppid
,gameId:this.gameId
}));
1340 this.compWorker
.postMessage(["init",fen
]);
1341 this.vr
= new VariantRules(fen
, moves
);
1342 if (moves
.length
> 0)
1344 const lastMove
= moves
[moves
.length
-1];
1345 this.vr
.undo(lastMove
);
1346 this.incheck
= this.vr
.getCheckSquares(lastMove
);
1347 this.vr
.play(lastMove
, "ingame");
1351 // Small delay required when continuation run faster than drawing page
1352 setTimeout(() => this.endGame(score
), 100);
1355 playComputerMove: function() {
1356 this.timeStart
= Date
.now();
1357 this.compWorker
.postMessage(["askmove"]);
1359 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1360 getSquareId: function(o
) {
1361 // NOTE: a separator is required to allow any size of board
1362 return "sq-" + o
.x
+ "-" + o
.y
;
1365 getSquareFromId: function(id
) {
1366 let idParts
= id
.split('-');
1367 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
1369 mousedown: function(e
) {
1370 e
= e
|| window
.event
;
1372 let elem
= e
.target
;
1373 while (!ingame
&& elem
!== null)
1375 if (elem
.classList
.contains("game"))
1380 elem
= elem
.parentElement
;
1382 if (!ingame
) //let default behavior (click on button...)
1384 e
.preventDefault(); //disable native drag & drop
1385 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
1387 // Next few lines to center the piece on mouse cursor
1388 let rect
= e
.target
.parentNode
.getBoundingClientRect();
1390 x: rect
.x
+ rect
.width
/2,
1391 y: rect
.y
+ rect
.width
/2,
1392 id: e
.target
.parentNode
.id
1394 this.selectedPiece
= e
.target
.cloneNode();
1395 this.selectedPiece
.style
.position
= "absolute";
1396 this.selectedPiece
.style
.top
= 0;
1397 this.selectedPiece
.style
.display
= "inline-block";
1398 this.selectedPiece
.style
.zIndex
= 3000;
1399 const startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1400 this.possibleMoves
= [];
1401 if (!["idle","chat"].includes(this.mode
))
1403 const color
= ["friend","problem"].includes(this.mode
)
1406 if (this.vr
.canIplay(color
,startSquare
))
1407 this.possibleMoves
= this.vr
.getPossibleMovesFrom(startSquare
);
1409 // Next line add moving piece just after current image
1410 // (required for Crazyhouse reserve)
1411 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1414 mousemove: function(e
) {
1415 if (!this.selectedPiece
)
1417 e
= e
|| window
.event
;
1418 // If there is an active element, move it around
1419 if (!!this.selectedPiece
)
1421 const [offsetX
,offsetY
] = !!e
.clientX
1422 ? [e
.clientX
,e
.clientY
] //desktop browser
1423 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1424 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1425 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1428 mouseup: function(e
) {
1429 if (!this.selectedPiece
)
1431 e
= e
|| window
.event
;
1432 // Read drop target (or parentElement, parentNode... if type == "img")
1433 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1434 const [offsetX
,offsetY
] = !!e
.clientX
1435 ? [e
.clientX
,e
.clientY
]
1436 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1437 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1438 this.selectedPiece
.style
.zIndex
= 3000;
1439 // Next condition: classList.contains(piece) fails because of marks
1440 while (landing
.tagName
== "IMG")
1441 landing
= landing
.parentNode
;
1442 if (this.start
.id
== landing
.id
)
1444 // A click: selectedPiece and possibleMoves are already filled
1447 // OK: process move attempt
1448 let endSquare
= this.getSquareFromId(landing
.id
);
1449 let moves
= this.findMatchingMoves(endSquare
);
1450 this.possibleMoves
= [];
1451 if (moves
.length
> 1)
1452 this.choices
= moves
;
1453 else if (moves
.length
==1)
1454 this.play(moves
[0]);
1455 // Else: impossible move
1456 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1457 delete this.selectedPiece
;
1458 this.selectedPiece
= null;
1460 findMatchingMoves: function(endSquare
) {
1461 // Run through moves list and return the matching set (if promotions...)
1463 this.possibleMoves
.forEach(function(m
) {
1464 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1469 animateMove: function(move) {
1470 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1471 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1472 let rectStart
= startSquare
.getBoundingClientRect();
1473 let rectEnd
= endSquare
.getBoundingClientRect();
1474 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1476 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1477 // HACK for animation (with positive translate, image slides "under background")
1478 // Possible improvement: just alter squares on the piece's way...
1479 squares
= document
.getElementsByClassName("board");
1480 for (let i
=0; i
<squares
.length
; i
++)
1482 let square
= squares
.item(i
);
1483 if (square
.id
!= this.getSquareId(move.start
))
1484 square
.style
.zIndex
= "-1";
1486 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1487 translation
.y
+ "px)";
1488 movingPiece
.style
.transitionDuration
= "0.2s";
1489 movingPiece
.style
.zIndex
= "3000";
1491 for (let i
=0; i
<squares
.length
; i
++)
1492 squares
.item(i
).style
.zIndex
= "auto";
1493 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1497 play: function(move, programmatic
) {
1500 // Navigate after game is over
1501 if (this.cursor
>= this.vr
.moves
.length
)
1502 return; //already at the end
1503 move = this.vr
.moves
[this.cursor
++];
1505 if (!!programmatic
) //computer or human opponent
1507 this.animateMove(move);
1510 // Not programmatic, or animation is over
1511 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1512 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1513 if (!["idle","chat"].includes(this.mode
))
1515 // Emergency check, if human game started "at the same time"
1516 // TODO: robustify this...
1517 if (this.mode
== "human" && !!move.computer
)
1519 this.incheck
= this.vr
.getCheckSquares(move); //is opponent in check?
1520 this.vr
.play(move, "ingame");
1521 if (this.sound
== 2)
1522 new Audio("/sounds/move.mp3").play().catch(err
=> {});
1523 if (this.mode
== "computer")
1525 // Send the move to web worker (TODO: including his own moves?!)
1526 this.compWorker
.postMessage(["newmove",move]);
1531 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1532 this.$forceUpdate(); //TODO: ?!
1534 if (!["idle","chat"].includes(this.mode
))
1536 const eog
= this.vr
.checkGameOver();
1539 if (["human","computer"].includes(this.mode
))
1543 // Just show score on screen (allow undo)
1545 this.showScoreMsg();
1549 if (["human","computer"].includes(this.mode
))
1550 this.updateStorage(); //after our moves and opponent moves
1551 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
&& this.score
== "*")
1552 this.playComputerMove();
1555 // Navigate after game is over
1556 if (this.cursor
== 0)
1557 return; //already at the beginning
1558 if (this.cursor
== this.vr
.moves
.length
)
1559 this.incheck
= []; //in case of...
1560 const move = this.vr
.moves
[--this.cursor
];
1561 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1562 this.$forceUpdate(); //TODO: ?!
1564 undoInGame: function() {
1565 const lm
= this.vr
.lastMove
;
1569 if (this.sound
== 2)
1570 new Audio("/sounds/undo.mp3").play().catch(err
=> {});
1571 const lmBefore
= this.vr
.lastMove
;
1574 this.vr
.undo(lmBefore
);
1575 this.incheck
= this.vr
.getCheckSquares(lmBefore
);
1576 this.vr
.play(lmBefore
, "ingame");