1 // Game logic on a variant page
2 Vue
.component('my-game', {
6 vr: null, //object to check moves, store them, FEN..
8 possibleMoves: [], //filled after each valid click/dragstart
9 choices: [], //promotion pieces, or checkered captures... (as moves)
10 start: {}, //pixels coordinates + id of starting square (click or drag)
11 selectedPiece: null, //moving piece (or clicked piece)
12 conn: null, //socket connection
13 score: "*", //'*' means 'unfinished'
14 mode: "idle", //human, friend, 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 bcolor: localStorage
["bcolor"] || "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",
63 [h('i', { 'class': { "material-icons": true } }, "accessibility")])
65 if (variant
!= "Dark" &&
66 (["idle","computer","friend"].includes(this.mode
)
67 || ["friend","human"].includes(this.mode
) && this.score
!= "*"))
72 on: { click: this.clickComputerGame
},
73 attrs: { "aria-label": translations
['New game versus computer'] },
77 "playing": this.mode
== "computer",
81 [h('i', { 'class': { "material-icons": true } }, "computer")])
84 if (variant
!= "Dark" &&
85 (["idle","friend"].includes(this.mode
)
86 || ["computer","human"].includes(this.mode
) && this.score
!= "*"))
91 on: { click: this.clickFriendGame
},
92 attrs: { "aria-label": translations
['Analysis mode'] },
96 "playing": this.mode
== "friend",
100 [h('i', { 'class': { "material-icons": true } }, "people")])
105 const square00
= document
.getElementById("sq-0-0");
106 const squareWidth
= !!square00
107 ? parseFloat(window
.getComputedStyle(square00
).width
.slice(0,-2))
109 const settingsBtnElt
= document
.getElementById("settingsBtn");
110 const settingsStyle
= !!settingsBtnElt
111 ? window
.getComputedStyle(settingsBtnElt
)
112 : {width:"46px", height:"26px"};
113 const [indicWidth
,indicHeight
] = //[44,24];
115 // NOTE: -2 for border
116 parseFloat(settingsStyle
.width
.slice(0,-2)) - 2,
117 parseFloat(settingsStyle
.height
.slice(0,-2)) - 2
119 let aboveBoardElts
= [];
120 if (this.mode
== "human")
122 const connectedIndic
= h(
127 "connected": this.oppConnected
,
128 "disconnected": !this.oppConnected
,
131 "width": indicWidth
+ "px",
132 "height": indicHeight
+ "px",
136 aboveBoardElts
.push(connectedIndic
);
138 if (this.mode
== "human" && this.score
!= "*")
140 const chatButton
= h(
143 on: { click: this.startChat
},
145 "aria-label": translations
['Start chat'],
155 [h('i', { 'class': { "material-icons": true } }, "chat")]
157 aboveBoardElts
.push(chatButton
);
159 if (["human","computer","friend"].includes(this.mode
))
161 const clearButton
= h(
164 on: { click: this.clearCurrentGame
},
166 "aria-label": translations
['Clear current game'],
176 [h('i', { 'class': { "material-icons": true } }, "clear")]
178 aboveBoardElts
.push(clearButton
);
185 "white-turn": this.vr
.turn
=="w",
186 "black-turn": this.vr
.turn
=="b",
189 "width": indicWidth
+ "px",
190 "height": indicHeight
+ "px",
194 aboveBoardElts
.push(turnIndic
);
195 const settingsBtn
= h(
198 on: { click: this.showSettings
},
200 "aria-label": translations
['Settings'],
210 [h('i', { 'class': { "material-icons": true } }, "settings")]
212 aboveBoardElts
.push(settingsBtn
);
215 { "class": { "aboveboard-wrapper": true } },
219 if (this.mode
== "problem")
221 // Show problem instructions
225 attrs: { id: "instructions-div" },
228 "section-content": true,
234 attrs: { id: "problem-instructions" },
235 domProps: { innerHTML: this.problem
.instructions
}
242 const choices
= h('div',
244 attrs: { "id": "choices" },
245 'class': { 'row': true },
247 "display": this.choices
.length
>0?"block":"none",
248 "top": "-" + ((sizeY
/2)*squareWidth+squareWidth/2) + "px",
249 "width": (this.choices
.length
* squareWidth
) + "px",
250 "height": squareWidth
+ "px",
253 this.choices
.map( m
=> { //a "choice" is a move
258 ['board'+sizeY
]: true,
261 'width': (100/this.choices
.length
) + "%",
262 'padding-bottom': (100/this.choices
.length
) + "%",
267 attrs: { "src": '/images/pieces/' +
268 VariantRules
.getPpath(m
.appear
[0].c
+m
.appear
[0].p
) + '.svg' },
269 'class': { 'choice-piece': true },
271 "click": e
=> { this.play(m
); this.choices
=[]; },
272 // NOTE: add 'touchstart' event to fix a problem on smartphones
273 "touchstart": e
=> { this.play(m
); this.choices
=[]; },
280 // Create board element (+ reserves if needed by variant or mode)
281 const lm
= this.vr
.lastMove
;
282 const showLight
= this.hints
&& variant
!="Dark" &&
283 (this.mode
!= "idle" ||
284 (this.vr
.moves
.length
> 0 && this.cursor
==this.vr
.moves
.length
));
285 const gameDiv
= h('div',
292 [_
.range(sizeX
).map(i
=> {
293 let ci
= (this.mycolor
=='w' ? i : sizeX
-i
-1);
300 style: { 'opacity': this.choices
.length
>0?"0.5":"1" },
302 _
.range(sizeY
).map(j
=> {
303 let cj
= (this.mycolor
=='w' ? j : sizeY
-j
-1);
305 if (this.vr
.board
[ci
][cj
] != VariantRules
.EMPTY
&& (variant
!="Dark"
306 || this.score
!="*" || this.vr
.enlightened
[this.mycolor
][ci
][cj
]))
314 'ghost': !!this.selectedPiece
315 && this.selectedPiece
.parentNode
.id
== "sq-"+ci
+"-"+cj
,
318 src: "/images/pieces/" +
319 VariantRules
.getPpath(this.vr
.board
[ci
][cj
]) + ".svg",
325 if (this.hints
&& hintSquares
[ci
][cj
])
335 src: "/images/mark.svg",
346 ['board'+sizeY
]: true,
347 'light-square': (i
+j
)%2==0,
348 'dark-square': (i
+j
)%2==1,
350 'in-shadow': variant
=="Dark" && this.score
=="*"
351 && !this.vr
.enlightened
[this.mycolor
][ci
][cj
],
352 'highlight': showLight
&& !!lm
&& _
.isMatch(lm
.end
, {x:ci
,y:cj
}),
353 'incheck': showLight
&& incheckSq
[ci
][cj
],
356 id: this.getSquareId({x:ci
,y:cj
}),
365 if (["human","computer"].includes(this.mode
))
367 if (this.score
== "*")
372 on: { click: this.resign
},
373 attrs: { "aria-label": translations
['Resign'] },
380 [h('i', { 'class': { "material-icons": true } }, "flag")])
385 // A game finished, and another is not started yet: allow navigation
386 actionArray
= actionArray
.concat([
389 on: { click: e
=> this.undo() },
390 attrs: { "aria-label": translations
['Undo'] },
393 "big-spaceleft": true,
396 [h('i', { 'class': { "material-icons": true } }, "fast_rewind")]),
399 on: { click: e
=> this.play() },
400 attrs: { "aria-label": translations
['Play'] },
406 [h('i', { 'class': { "material-icons": true } }, "fast_forward")]),
411 if (["friend","problem"].includes(this.mode
))
413 actionArray
= actionArray
.concat(
417 on: { click: this.undoInGame
},
418 attrs: { "aria-label": translations
['Undo'] },
421 "big-spaceleft": true,
424 [h('i', { 'class': { "material-icons": true } }, "undo")]
428 on: { click: () => { this.mycolor
= this.vr
.getOppCol(this.mycolor
) } },
429 attrs: { "aria-label": translations
['Flip board'] },
435 [h('i', { 'class': { "material-icons": true } }, "cached")]
439 elementArray
.push(gameDiv
);
440 if (!!this.vr
.reserve
)
442 const shiftIdx
= (this.mycolor
=="w" ? 0 : 1);
443 let myReservePiecesArray
= [];
444 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
446 myReservePiecesArray
.push(h('div',
448 'class': {'board':true, ['board'+sizeY
+'-reserve']:true},
449 attrs: { id: this.getSquareId({x:sizeX
+shiftIdx
,y:i
}) }
454 'class': {"piece":true, "reserve":true},
456 "src": "/images/pieces/" +
457 this.vr
.getReservePpath(this.mycolor
,i
) + ".svg",
461 {"class": { "reserve-count": true } },
462 [ this.vr
.reserve
[this.mycolor
][VariantRules
.RESERVE_PIECES
[i
]] ]
466 let oppReservePiecesArray
= [];
467 const oppCol
= this.vr
.getOppCol(this.mycolor
);
468 for (let i
=0; i
<VariantRules
.RESERVE_PIECES
.length
; i
++)
470 oppReservePiecesArray
.push(h('div',
472 'class': {'board':true, ['board'+sizeY
+'-reserve']:true},
473 attrs: { id: this.getSquareId({x:sizeX
+(1-shiftIdx
),y:i
}) }
478 'class': {"piece":true, "reserve":true},
480 "src": "/images/pieces/" +
481 this.vr
.getReservePpath(oppCol
,i
) + ".svg",
485 {"class": { "reserve-count": true } },
486 [ this.vr
.reserve
[oppCol
][VariantRules
.RESERVE_PIECES
[i
]] ]
490 let reserves
= h('div',
502 "reserve-row-1": true,
508 { 'class': { 'row': true }},
509 oppReservePiecesArray
513 elementArray
.push(reserves
);
518 attrs: { "id": "modal-eog", type: "checkbox" },
519 "class": { "modal": true },
523 attrs: { "role": "dialog", "aria-labelledby": "eogMessage" },
538 attrs: { "for": "modal-eog" },
539 "class": { "modal-close": true },
544 attrs: { "id": "eogMessage" },
545 "class": { "section": true },
546 domProps: { innerHTML: this.endgameMessage
},
554 elementArray
= elementArray
.concat(modalEog
);
556 const modalFenEdit
= [
559 attrs: { "id": "modal-fenedit", type: "checkbox" },
560 "class": { "modal": true },
564 attrs: { "role": "dialog", "aria-labelledby": "titleFenedit" },
569 "class": { "card": true, "smallpad": true },
574 attrs: { "id": "close-fenedit", "for": "modal-fenedit" },
575 "class": { "modal-close": true },
580 attrs: { "id": "titleFenedit" },
581 "class": { "section": true },
582 domProps: { innerHTML: translations
["Game state (FEN):"] },
590 value: VariantRules
.GenRandInitFen(),
598 const fen
= document
.getElementById("input-fen").value
;
599 document
.getElementById("modal-fenedit").checked
= false;
600 this.newGame("friend", fen
);
603 domProps: { innerHTML: translations
["Ok"] },
610 document
.getElementById("input-fen").value
=
611 VariantRules
.GenRandInitFen();
614 domProps: { innerHTML: translations
["Random"] },
622 elementArray
= elementArray
.concat(modalFenEdit
);
623 const modalSettings
= [
626 attrs: { "id": "modal-settings", type: "checkbox" },
627 "class": { "modal": true },
631 attrs: { "role": "dialog", "aria-labelledby": "settingsTitle" },
636 "class": { "card": true, "smallpad": true },
641 attrs: { "id": "close-settings", "for": "modal-settings" },
642 "class": { "modal-close": true },
647 attrs: { "id": "settingsTitle" },
648 "class": { "section": true },
649 domProps: { innerHTML: translations
["Preferences"] },
657 attrs: { for: "nameSetter" },
658 domProps: { innerHTML: translations
["My name is..."] },
668 on: { "change": this.setMyname
},
678 attrs: { for: "setHints" },
679 domProps: { innerHTML: translations
["Show hints?"] },
689 on: { "change": this.toggleHints
},
699 attrs: { for: "selectColor" },
700 domProps: { innerHTML: translations
["Board colors"] },
705 attrs: { "id": "selectColor" },
706 on: { "change": this.setBoardColor
},
713 innerHTML: translations
["brown"]
715 attrs: { "selected": this.color
=="lichess" },
722 innerHTML: translations
["green"]
724 attrs: { "selected": this.color
=="chesscom" },
730 "value": "chesstempo",
731 innerHTML: translations
["blue"]
733 attrs: { "selected": this.color
=="chesstempo" },
745 attrs: { for: "selectSound" },
746 domProps: { innerHTML: translations
["Play sounds?"] },
751 attrs: { "id": "selectSound" },
752 on: { "change": this.setSound
},
759 innerHTML: translations
["None"]
761 attrs: { "selected": this.sound
==0 },
768 innerHTML: translations
["New game"]
770 attrs: { "selected": this.sound
==1 },
777 innerHTML: translations
["All"]
779 attrs: { "selected": this.sound
==2 },
791 elementArray
= elementArray
.concat(modalSettings
);
796 attrs: { "id": "close-chat", "for": "modal-chat" },
797 "class": { "modal-close": true },
802 attrs: { "id": "titleChat" },
803 "class": { "section": true },
804 domProps: { innerHTML: translations
["Chat with "] + this.oppName
},
808 for (let chat
of this.chats
)
814 "my-chatmsg": chat
.author
==this.myid
,
815 "opp-chatmsg": chat
.author
==this.oppid
,
817 domProps: { innerHTML: chat
.msg
}
822 chatEltsArray
= chatEltsArray
.concat([
828 placeholder: translations
["Type here"],
830 on: { keyup: this.trySendChat
}, //if key is 'enter'
835 attrs: { id: "sendChatBtn"},
836 on: { click: this.sendChat
},
837 domProps: { innerHTML: translations
["Send"] },
844 attrs: { "id": "modal-chat", type: "checkbox" },
845 "class": { "modal": true },
849 attrs: { "role": "dialog", "aria-labelledby": "titleChat" },
854 "class": { "card": true, "smallpad": true },
861 elementArray
= elementArray
.concat(modalChat
);
862 const actions
= h('div',
864 attrs: { "id": "actions" },
865 'class': { 'text-center': true },
869 elementArray
.push(actions
);
870 if (this.score
!= "*" && this.pgnTxt
.length
> 0)
875 attrs: { id: "pgn-div" },
876 "class": { "section-content": true },
889 attrs: { id: "pgn-game" },
890 domProps: { innerHTML: this.pgnTxt
}
895 attrs: { "id": "downloadBtn" },
896 on: { click: this.download
},
897 domProps: { innerHTML: translations
["Download game"] },
904 else if (this.mode
!= "idle")
906 if (this.mode
== "problem")
908 // Show problem solution (on click)
912 attrs: { id: "solution-div" },
913 "class": { "section-content": true },
918 "class": { clickable: true },
919 domProps: { innerHTML: translations
["Show solution"] },
920 on: { click: this.toggleShowSolution
},
925 attrs: { id: "problem-solution" },
926 domProps: { innerHTML: this.problem
.solution
}
933 if (variant
!= "Dark" || this.score
!="*")
939 attrs: { id: "fen-div" },
940 "class": { "section-content": true },
945 attrs: { id: "fen-string" },
946 domProps: { innerHTML: this.vr
.getBaseFen() },
947 "class": { "text-center": true },
961 "col-md-offset-1":true,
963 "col-lg-offset-2":true,
965 // NOTE: click = mousedown + mouseup
967 mousedown: this.mousedown
,
968 mousemove: this.mousemove
,
969 mouseup: this.mouseup
,
970 touchstart: this.mousedown
,
971 touchmove: this.mousemove
,
972 touchend: this.mouseup
,
979 endgameMessage: function() {
980 let eogMessage
= "Unfinished";
984 eogMessage
= translations
["White win"];
987 eogMessage
= translations
["Black win"];
990 eogMessage
= translations
["Draw"];
996 created: function() {
997 const url
= socketUrl
;
998 const humanContinuation
= (localStorage
.getItem("variant") === variant
);
999 const computerContinuation
= (localStorage
.getItem("comp-variant") === variant
);
1000 const friendContinuation
= (localStorage
.getItem("anlz-variant") === variant
);
1001 this.myid
= (humanContinuation
? localStorage
.getItem("myid") : getRandString());
1002 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
1003 const socketOpenListener
= () => {
1004 if (humanContinuation
) //game VS human has priority
1005 this.continueGame("human");
1006 else if (computerContinuation
)
1007 this.continueGame("computer");
1008 else if (friendContinuation
)
1009 this.continueGame("friend");
1011 const socketMessageListener
= msg
=> {
1012 const data
= JSON
.parse(msg
.data
);
1013 const L
= (!!this.vr
? this.vr
.moves
.length : 0);
1017 // Receive opponent's name
1018 this.oppName
= data
.name
;
1022 this.chats
.push({msg:data
.msg
, author:this.oppid
});
1025 // We opened another tab on the same game
1029 "Already playing a game in this variant on another tab!"]);
1031 case "newgame": //opponent found
1032 // oppid: opponent socket ID
1033 this.newGame("human", data
.fen
, data
.color
, data
.oppid
);
1035 case "newmove": //..he played!
1036 this.play(data
.move, (variant
!="Dark" ? "animate" : null));
1038 case "pong": //received if we sent a ping (game still alive on our side)
1039 if (this.gameId
!= data
.gameId
)
1040 break; //games IDs don't match: definitely over...
1041 this.oppConnected
= true;
1042 // Send our "last state" informations to opponent
1043 this.conn
.send(JSON
.stringify({
1046 gameId: this.gameId
,
1047 lastMove: (L
>0?this.vr
.moves
[L
-1]:undefined),
1051 case "lastate": //got opponent infos about last move
1052 if (this.gameId
!= data
.gameId
)
1053 break; //games IDs don't match: nothing we can do...
1054 // OK, opponent still in game (which might be over)
1055 if (this.mode
!= "human")
1057 // We finished the game (any result possible)
1058 this.conn
.send(JSON
.stringify({
1061 gameId: this.gameId
,
1065 else if (!!data
.score
) //opponent finished the game
1066 this.endGame(data
.score
);
1067 else if (data
.movesCount
< L
)
1069 // We must tell last move to opponent
1070 this.conn
.send(JSON
.stringify({
1073 lastMove: this.vr
.moves
[L
-1],
1077 else if (data
.movesCount
> L
) //just got last move from him
1078 this.play(data
.lastMove
, "animate");
1080 case "resign": //..you won!
1081 this.endGame(this.mycolor
=="w"?"1-0":"0-1");
1083 // TODO: also use (dis)connect info to count online players?
1086 if (this.mode
=="human" && this.oppid
== data
.id
)
1087 this.oppConnected
= (data
.code
== "connect");
1088 if (this.oppConnected
&& this.score
!= "*")
1090 // Send our name to the opponent, in case of he hasn't it
1091 this.conn
.send(JSON
.stringify({
1092 code:"myname", name:this.myname
, oppid: this.oppid
}));
1097 const socketCloseListener
= () => {
1098 this.conn
= new WebSocket(url
+ "/?sid=" + this.myid
+ "&page=" + variant
);
1099 this.conn
.addEventListener('open', socketOpenListener
);
1100 this.conn
.addEventListener('message', socketMessageListener
);
1101 this.conn
.addEventListener('close', socketCloseListener
);
1103 this.conn
.onopen
= socketOpenListener
;
1104 this.conn
.onmessage
= socketMessageListener
;
1105 this.conn
.onclose
= socketCloseListener
;
1106 // Listen to keyboard left/right to navigate in game
1107 document
.onkeydown
= event
=> {
1108 if (["human","computer"].includes(this.mode
) &&
1109 !!this.vr
&& this.vr
.moves
.length
> 0 && [37,39].includes(event
.keyCode
))
1111 event
.preventDefault();
1112 if (event
.keyCode
== 37) //Back
1118 // Computer moves web worker logic:
1119 this.compWorker
.postMessage(["scripts",variant
]);
1121 this.compWorker
.onmessage = function(e
) {
1122 let compMove
= e
.data
;
1124 return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...)
1125 if (!Array
.isArray(compMove
))
1126 compMove
= [compMove
]; //to deal with MarseilleRules
1127 // TODO: imperfect attempt to avoid ghost move:
1128 compMove
.forEach(m
=> { m
.computer
= true; });
1129 // (first move) HACK: small delay to avoid selecting elements
1130 // before they appear on page:
1131 const delay
= Math
.max(500-(Date
.now()-self
.timeStart
), 0);
1133 if (self
.mode
== "computer") //warning: mode could have changed!
1134 self
.play(compMove
[0], "animate");
1135 if (compMove
.length
== 2)
1137 if (self
.mode
== "computer")
1138 self
.play(compMove
[1], "animate");
1144 setMyname: function(e
) {
1145 this.myname
= e
.target
.value
;
1146 localStorage
["username"] = this.myname
;
1148 trySendChat: function(e
) {
1149 if (e
.keyCode
== 13) //'enter' key
1152 sendChat: function() {
1153 let chatInput
= document
.getElementById("input-chat");
1154 const chatTxt
= chatInput
.value
;
1155 chatInput
.value
= "";
1156 this.chats
.push({msg:chatTxt
, author:this.myid
});
1157 this.conn
.send(JSON
.stringify({
1158 code:"newchat", oppid: this.oppid
, msg: chatTxt
}));
1160 toggleShowSolution: function() {
1161 let problemSolution
= document
.getElementById("problem-solution");
1162 problemSolution
.style
.display
=
1163 !problemSolution
.style
.display
|| problemSolution
.style
.display
== "none"
1167 download: function() {
1168 let content
= document
.getElementById("pgn-game").innerHTML
;
1169 content
= content
.replace(/<br>/g, "\n");
1170 // Prepare and trigger download link
1171 let downloadAnchor
= document
.getElementById("download");
1172 downloadAnchor
.setAttribute("download", "game.pgn");
1173 downloadAnchor
.href
= "data:text/plain;charset=utf-8," +
1174 encodeURIComponent(content
);
1175 downloadAnchor
.click();
1177 showScoreMsg: function() {
1178 let modalBox
= document
.getElementById("modal-eog");
1179 modalBox
.checked
= true;
1180 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1182 endGame: function(score
) {
1184 if (["human","computer"].includes(this.mode
))
1186 const prefix
= (this.mode
=="computer" ? "comp-" : "");
1187 localStorage
.setItem(prefix
+"score", score
);
1189 this.showScoreMsg();
1190 // Variants may have special PGN structure (so next function isn't defined here)
1191 this.pgnTxt
= this.vr
.getPGN(this.mycolor
, this.score
, this.fenStart
, this.mode
);
1192 if (this.mode
== "human" && this.oppConnected
)
1194 // Send our nickname to opponent
1195 this.conn
.send(JSON
.stringify({
1196 code:"myname", name:this.myname
, oppid:this.oppid
}));
1198 this.cursor
= this.vr
.moves
.length
; //to navigate in finished game
1200 getStoragePrefix: function(mode
) {
1202 if (mode
== "computer")
1204 else if (mode
== "friend")
1208 setStorage: function() {
1209 if (this.mode
=="human")
1211 localStorage
.setItem("myid", this.myid
);
1212 localStorage
.setItem("oppid", this.oppid
);
1213 localStorage
.setItem("gameId", this.gameId
);
1215 const prefix
= this.getStoragePrefix(this.mode
);
1216 localStorage
.setItem(prefix
+"variant", variant
);
1217 localStorage
.setItem(prefix
+"mycolor", this.mycolor
);
1218 localStorage
.setItem(prefix
+"fenStart", this.fenStart
);
1219 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1220 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1221 localStorage
.setItem(prefix
+"score", "*");
1223 updateStorage: function() {
1224 const prefix
= this.getStoragePrefix(this.mode
);
1225 localStorage
.setItem(prefix
+"moves", JSON
.stringify(this.vr
.moves
));
1226 localStorage
.setItem(prefix
+"fen", this.vr
.getFen());
1227 if (this.score
!= "*")
1228 localStorage
.setItem(prefix
+"score", this.score
);
1230 // "computer mode" clearing is done through the menu
1231 clearStorage: function() {
1232 if (this.mode
== "human")
1234 delete localStorage
["myid"];
1235 delete localStorage
["oppid"];
1236 delete localStorage
["gameId"];
1238 const prefix
= this.getStoragePrefix(this.mode
);
1239 delete localStorage
[prefix
+"variant"];
1240 delete localStorage
[prefix
+"mycolor"];
1241 delete localStorage
[prefix
+"fenStart"];
1242 delete localStorage
[prefix
+"moves"];
1243 delete localStorage
[prefix
+"fen"];
1244 delete localStorage
[prefix
+"score"];
1246 // HACK because mini-css tooltips are persistent after click...
1247 // NOTE: seems to work only in chrome/chromium. TODO...
1248 getRidOfTooltip: function(elt
) {
1249 elt
.style
.visibility
= "hidden";
1250 setTimeout(() => { elt
.style
.visibility
="visible"; }, 100);
1252 startChat: function(e
) {
1253 this.getRidOfTooltip(e
.currentTarget
);
1254 document
.getElementById("modal-chat").checked
= true;
1256 clearCurrentGame: function(e
) {
1257 this.getRidOfTooltip(e
.currentTarget
);
1258 this.clearStorage();
1259 location
.reload(); //to see clearing effects
1261 showSettings: function(e
) {
1262 this.getRidOfTooltip(e
.currentTarget
);
1263 document
.getElementById("modal-settings").checked
= true;
1265 toggleHints: function() {
1266 this.hints
= !this.hints
;
1267 localStorage
["hints"] = (this.hints
? "1" : "0");
1269 setBoardColor: function(e
) {
1270 this.bcolor
= e
.target
.options
[e
.target
.selectedIndex
].value
;
1271 localStorage
["bcolor"] = this.bcolor
;
1273 setSound: function(e
) {
1274 this.sound
= parseInt(e
.target
.options
[e
.target
.selectedIndex
].value
);
1275 localStorage
["sound"] = this.sound
;
1277 clickGameSeek: function(e
) {
1278 this.getRidOfTooltip(e
.currentTarget
);
1279 if (this.mode
== "human")
1280 return; //no newgame while playing
1283 this.conn
.send(JSON
.stringify({code:"cancelnewgame"}));
1287 this.newGame("human");
1289 clickComputerGame: function(e
) {
1290 this.getRidOfTooltip(e
.currentTarget
);
1291 this.newGame("computer");
1293 clickFriendGame: function(e
) {
1294 this.getRidOfTooltip(e
.currentTarget
);
1295 document
.getElementById("modal-fenedit").checked
= true;
1297 resign: function(e
) {
1298 this.getRidOfTooltip(e
.currentTarget
);
1299 if (this.mode
== "human" && this.oppConnected
)
1302 this.conn
.send(JSON
.stringify({code: "resign", oppid: this.oppid
}));
1303 } catch (INVALID_STATE_ERR
) {
1304 return; //socket is not ready (and not yet reconnected)
1307 this.endGame(this.mycolor
=="w"?"0-1":"1-0");
1309 newGame: function(mode
, fenInit
, color
, oppId
) {
1310 const fen
= fenInit
|| VariantRules
.GenRandInitFen();
1311 console
.log(fen
); //DEBUG
1312 if (mode
=="human" && !oppId
)
1314 const storageVariant
= localStorage
.getItem("variant");
1315 if (!!storageVariant
&& storageVariant
!== variant
1316 && localStorage
["score"] == "*")
1318 return alert(translations
["Finish your "] +
1319 storageVariant
+ translations
[" game first!"]);
1321 // Send game request and wait..
1323 this.conn
.send(JSON
.stringify({code:"newgame", fen:fen
}));
1324 } catch (INVALID_STATE_ERR
) {
1325 return; //nothing achieved
1328 let modalBox
= document
.getElementById("modal-newgame");
1329 modalBox
.checked
= true;
1330 setTimeout(() => { modalBox
.checked
= false; }, 2000);
1333 const prefix
= this.getStoragePrefix(mode
);
1334 if (mode
== "computer")
1336 const storageVariant
= localStorage
.getItem(prefix
+"variant");
1337 if (!!storageVariant
)
1339 const score
= localStorage
.getItem(prefix
+"score");
1340 if (storageVariant
!== variant
&& score
== "*")
1342 if (!confirm(storageVariant
+
1343 translations
[": unfinished computer game will be erased"]))
1348 else if (score
== "*")
1349 return this.continueGame("computer");
1352 else if (mode
== "friend")
1354 const storageVariant
= localStorage
.getItem(prefix
+"variant");
1355 if (!!storageVariant
)
1357 const score
= localStorage
.getItem(prefix
+"score");
1358 if (storageVariant
!== variant
&& score
== "*")
1360 if (!confirm(storageVariant
+
1361 translations
[": current analysis will be erased"]))
1368 this.vr
= new VariantRules(fen
, []);
1370 this.pgnTxt
= ""; //redundant with this.score = "*", but cleaner
1373 this.fenStart
= V
.ParseFen(fen
).position
; //this is enough
1374 if (mode
!= "problem")
1375 this.setStorage(); //store game state in case of interruptions
1379 this.gameId
= getRandString();
1381 this.oppConnected
= true;
1382 this.mycolor
= color
;
1384 if (this.sound
>= 1)
1385 new Audio("/sounds/newgame.mp3").play().catch(err
=> {});
1386 document
.getElementById("modal-newgame").checked
= false;
1388 else if (mode
== "computer")
1390 this.compWorker
.postMessage(["init",this.vr
.getFen()]);
1391 this.mycolor
= (Math
.random() < 0.5 ? 'w' : 'b');
1392 if (this.mycolor
!= this.vr
.turn
)
1393 this.playComputerMove();
1395 else if (mode
== "friend")
1396 this.mycolor
= "w"; //convention...
1397 //else: problem solving: nothing more to do
1399 continueGame: function(mode
) {
1401 this.oppid
= (mode
=="human" ? localStorage
.getItem("oppid") : undefined);
1402 const prefix
= this.getStoragePrefix(mode
);
1403 this.mycolor
= localStorage
.getItem(prefix
+"mycolor");
1404 const moves
= JSON
.parse(localStorage
.getItem(prefix
+"moves"));
1405 const fen
= localStorage
.getItem(prefix
+"fen");
1406 const score
= localStorage
.getItem(prefix
+"score"); //set in "endGame()"
1407 this.fenStart
= localStorage
.getItem(prefix
+"fenStart");
1408 this.vr
= new VariantRules(fen
, moves
);
1409 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
1410 if (mode
== "human")
1412 this.gameId
= localStorage
.getItem("gameId");
1413 // Send ping to server (answer pong if opponent is connected)
1414 this.conn
.send(JSON
.stringify({
1415 code:"ping",oppid:this.oppid
,gameId:this.gameId
}));
1417 else if (mode
== "computer")
1419 this.compWorker
.postMessage(["init",fen
]);
1420 if (this.mycolor
!= this.vr
.turn
)
1421 this.playComputerMove();
1423 //else: nothing special to do in friend mode
1426 // Small delay required when continuation run faster than drawing page
1427 setTimeout(() => this.endGame(score
), 100);
1430 playComputerMove: function() {
1431 this.timeStart
= Date
.now();
1432 this.compWorker
.postMessage(["askmove"]);
1434 // Get the identifier of a HTML table cell from its numeric coordinates o.x,o.y.
1435 getSquareId: function(o
) {
1436 // NOTE: a separator is required to allow any size of board
1437 return "sq-" + o
.x
+ "-" + o
.y
;
1440 getSquareFromId: function(id
) {
1441 let idParts
= id
.split('-');
1442 return [parseInt(idParts
[1]), parseInt(idParts
[2])];
1444 mousedown: function(e
) {
1445 e
= e
|| window
.event
;
1447 let elem
= e
.target
;
1448 while (!ingame
&& elem
!== null)
1450 if (elem
.classList
.contains("game"))
1455 elem
= elem
.parentElement
;
1457 if (!ingame
) //let default behavior (click on button...)
1459 e
.preventDefault(); //disable native drag & drop
1460 if (!this.selectedPiece
&& e
.target
.classList
.contains("piece"))
1462 // Next few lines to center the piece on mouse cursor
1463 let rect
= e
.target
.parentNode
.getBoundingClientRect();
1465 x: rect
.x
+ rect
.width
/2,
1466 y: rect
.y
+ rect
.width
/2,
1467 id: e
.target
.parentNode
.id
1469 this.selectedPiece
= e
.target
.cloneNode();
1470 this.selectedPiece
.style
.position
= "absolute";
1471 this.selectedPiece
.style
.top
= 0;
1472 this.selectedPiece
.style
.display
= "inline-block";
1473 this.selectedPiece
.style
.zIndex
= 3000;
1474 const startSquare
= this.getSquareFromId(e
.target
.parentNode
.id
);
1475 this.possibleMoves
= [];
1476 if (this.score
== "*")
1478 const color
= ["friend","problem"].includes(this.mode
)
1481 if (this.vr
.canIplay(color
,startSquare
))
1482 this.possibleMoves
= this.vr
.getPossibleMovesFrom(startSquare
);
1484 // Next line add moving piece just after current image
1485 // (required for Crazyhouse reserve)
1486 e
.target
.parentNode
.insertBefore(this.selectedPiece
, e
.target
.nextSibling
);
1489 mousemove: function(e
) {
1490 if (!this.selectedPiece
)
1492 e
= e
|| window
.event
;
1493 // If there is an active element, move it around
1494 if (!!this.selectedPiece
)
1496 const [offsetX
,offsetY
] = !!e
.clientX
1497 ? [e
.clientX
,e
.clientY
] //desktop browser
1498 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
]; //smartphone
1499 this.selectedPiece
.style
.left
= (offsetX
-this.start
.x
) + "px";
1500 this.selectedPiece
.style
.top
= (offsetY
-this.start
.y
) + "px";
1503 mouseup: function(e
) {
1504 if (!this.selectedPiece
)
1506 e
= e
|| window
.event
;
1507 // Read drop target (or parentElement, parentNode... if type == "img")
1508 this.selectedPiece
.style
.zIndex
= -3000; //HACK to find square from final coords
1509 const [offsetX
,offsetY
] = !!e
.clientX
1510 ? [e
.clientX
,e
.clientY
]
1511 : [e
.changedTouches
[0].pageX
, e
.changedTouches
[0].pageY
];
1512 let landing
= document
.elementFromPoint(offsetX
, offsetY
);
1513 this.selectedPiece
.style
.zIndex
= 3000;
1514 // Next condition: classList.contains(piece) fails because of marks
1515 while (landing
.tagName
== "IMG")
1516 landing
= landing
.parentNode
;
1517 if (this.start
.id
== landing
.id
)
1519 // A click: selectedPiece and possibleMoves are already filled
1522 // OK: process move attempt
1523 let endSquare
= this.getSquareFromId(landing
.id
);
1524 let moves
= this.findMatchingMoves(endSquare
);
1525 this.possibleMoves
= [];
1526 if (moves
.length
> 1)
1527 this.choices
= moves
;
1528 else if (moves
.length
==1)
1529 this.play(moves
[0]);
1530 // Else: impossible move
1531 this.selectedPiece
.parentNode
.removeChild(this.selectedPiece
);
1532 delete this.selectedPiece
;
1533 this.selectedPiece
= null;
1535 findMatchingMoves: function(endSquare
) {
1536 // Run through moves list and return the matching set (if promotions...)
1538 this.possibleMoves
.forEach(function(m
) {
1539 if (endSquare
[0] == m
.end
.x
&& endSquare
[1] == m
.end
.y
)
1544 animateMove: function(move) {
1545 let startSquare
= document
.getElementById(this.getSquareId(move.start
));
1546 let endSquare
= document
.getElementById(this.getSquareId(move.end
));
1547 let rectStart
= startSquare
.getBoundingClientRect();
1548 let rectEnd
= endSquare
.getBoundingClientRect();
1549 let translation
= {x:rectEnd
.x
-rectStart
.x
, y:rectEnd
.y
-rectStart
.y
};
1551 document
.querySelector("#" + this.getSquareId(move.start
) + " > img.piece");
1552 // HACK for animation (with positive translate, image slides "under background")
1553 // Possible improvement: just alter squares on the piece's way...
1554 squares
= document
.getElementsByClassName("board");
1555 for (let i
=0; i
<squares
.length
; i
++)
1557 let square
= squares
.item(i
);
1558 if (square
.id
!= this.getSquareId(move.start
))
1559 square
.style
.zIndex
= "-1";
1561 movingPiece
.style
.transform
= "translate(" + translation
.x
+ "px," +
1562 translation
.y
+ "px)";
1563 movingPiece
.style
.transitionDuration
= "0.2s";
1564 movingPiece
.style
.zIndex
= "3000";
1566 for (let i
=0; i
<squares
.length
; i
++)
1567 squares
.item(i
).style
.zIndex
= "auto";
1568 movingPiece
.style
= {}; //required e.g. for 0-0 with KR swap
1572 play: function(move, programmatic
) {
1575 // Navigate after game is over
1576 if (this.cursor
>= this.vr
.moves
.length
)
1577 return; //already at the end
1578 move = this.vr
.moves
[this.cursor
++];
1580 if (!!programmatic
) //computer or human opponent
1581 return this.animateMove(move);
1582 // Not programmatic, or animation is over
1583 if (this.mode
== "human" && this.vr
.turn
== this.mycolor
)
1584 this.conn
.send(JSON
.stringify({code:"newmove", move:move, oppid:this.oppid
}));
1585 if (this.score
== "*")
1587 // Emergency check, if human game started "at the same time"
1588 // TODO: robustify this...
1589 if (this.mode
== "human" && !!move.computer
)
1591 this.vr
.play(move, "ingame");
1592 // Is opponent in check?
1593 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);
1594 if (this.sound
== 2)
1595 new Audio("/sounds/move.mp3").play().catch(err
=> {});
1596 if (this.mode
== "computer")
1598 // Send the move to web worker (TODO: including his own moves?!)
1599 this.compWorker
.postMessage(["newmove",move]);
1601 const eog
= this.vr
.checkGameOver();
1604 if (["human","computer"].includes(this.mode
))
1608 // Just show score on screen (allow undo)
1610 this.showScoreMsg();
1616 VariantRules
.PlayOnBoard(this.vr
.board
, move);
1617 this.$forceUpdate(); //TODO: ?!
1619 if (["human","computer","friend"].includes(this.mode
))
1620 this.updateStorage(); //after our moves and opponent moves
1621 if (this.mode
== "computer" && this.vr
.turn
!= this.mycolor
&& this.score
== "*")
1622 this.playComputerMove();
1625 // Navigate after game is over
1626 if (this.cursor
== 0)
1627 return; //already at the beginning
1628 if (this.cursor
== this.vr
.moves
.length
)
1629 this.incheck
= []; //in case of...
1630 const move = this.vr
.moves
[--this.cursor
];
1631 VariantRules
.UndoOnBoard(this.vr
.board
, move);
1632 this.$forceUpdate(); //TODO: ?!
1634 undoInGame: function() {
1635 const lm
= this.vr
.lastMove
;
1639 if (this.sound
== 2)
1640 new Audio("/sounds/undo.mp3").play().catch(err
=> {});
1641 this.incheck
= this.vr
.getCheckSquares(this.vr
.turn
);