TODO: modalSettings + finish game.js for other scenarios
[vchess.git] / public / javascripts / components / game.js
CommitLineData
fd373b27 1// TODO: envoyer juste "light move", sans FEN ni notation ...etc
2305d34a 2// TODO: also "observers" prop, we should send moves to them too (in a web worker ? webRTC ?)
fd373b27 3// Game logic on a variant page: 3 modes, analyze, computer or human
1d184b4c 4Vue.component('my-game', {
fd373b27 5 // gameId: to find the game in storage (assumption: it exists)
81bc1102 6 // fen: to start from a FEN without identifiers (analyze mode)
d44df0b0 7 props: ["conn","gameId","fen","mode","allowChat","allowMovelist"],
1d184b4c
BA
8 data: function() {
9 return {
fd373b27 10 oppConnected: false, //TODO?
a897b421 11 // sound level: 0 = no sound, 1 = sound only on newgame, 2 = always
e6dcb115 12 sound: parseInt(localStorage["sound"] || "2"),
643479f8
BA
13 // Web worker to play computer moves without freezing interface:
14 compWorker: new Worker('/javascripts/playCompMove.js'),
15 timeStart: undefined, //time when computer starts thinking
fd373b27 16 vr: null, //VariantRules object, describing the game state + rules
d44df0b0
BA
17 endgameMessage: "",
18 orientation: "w",
59d58d7d
BA
19
20 // if oppid == "computer" then mode = "computer" (otherwise human)
21 oppid: "", //opponent ID in case of HH game
22 score: "*", //'*' means 'unfinished'
23 // userColor: given by gameId, or fen (if no game Id)
24 mycolor: "w",
7d9e99bc 25 fenStart: "",
d44df0b0 26 moves: [], //TODO: initialize if gameId is defined...
7d9e99bc 27 cursor: 0,
59d58d7d 28 lastMove: null,
1d184b4c
BA
29 };
30 },
fd08ab2c
BA
31 watch: {
32 fen: function(newFen) {
33 this.vr = new VariantRules(newFen);
34 },
d44df0b0
BA
35 gameId: function() {
36 this.loadGame();
37 },
fd08ab2c 38 },
81da2786 39 computed: {
81da2786 40 showChat: function() {
fd373b27 41 return this.allowChat && this.mode=='human' && this.score != '*';
81da2786
BA
42 },
43 showMoves: function() {
7d9e99bc 44 return true;
fd373b27
BA
45 return this.allowMovelist && window.innerWidth >= 768;
46 },
47 showFen: function() {
48 return variant.name != "Dark" || this.score != "*";
c794dbb8
BA
49 },
50 },
81da2786 51 // Modal end of game, and then sub-components
fd373b27 52 // TODO: provide chat parameters (connection, players ID...)
fd373b27 53 // TODO: controls: abort, clear, resign, draw (avec confirm box)
81da2786
BA
54 template: `
55 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
56 <input id="modal-eog" type="checkbox" class="modal"/>
57 <div role="dialog" aria-labelledby="eogMessage">
58 <div class="card smallpad small-modal text-center">
fd373b27
BA
59 <label for="modal-eog" class="modal-close">
60 </label>
61 <h3 id="eogMessage" class="section">
62 {{ endgameMessage }}
63 </h3>
936dc463
BA
64 </div>
65 </div>
fd373b27
BA
66 <my-chat v-if="showChat">
67 </my-chat>
59d58d7d 68 <my-board v-bind:vr="vr" :last-move="lastMove" :mode="mode" :orientation="orientation" :user-color="mycolor" @play-move="play">
fd373b27 69 </my-board>
7d9e99bc
BA
70 <div class="button-group">
71 <button @click="() => play()">Play</button>
72 <button @click="() => undo()">Undo</button>
73 <button @click="flip">Flip</button>
74 <button @click="gotoBegin">GotoBegin</button>
75 <button @click="gotoEnd">GotoEnd</button>
76 </div>
d44df0b0 77 <div v-if="showFen && !!vr" id="fen-div" class="section-content">
fd373b27
BA
78 <p id="fen-string" class="text-center">
79 {{ vr.getFen() }}
80 </p>
81 </div>
81da2786 82 <div id="pgn-div" class="section-content">
4608eed9 83 <a id="download" href="#">
fd373b27 84 </a>
81da2786 85 <button id="downloadBtn" @click="download">
d44df0b0 86 {{ translate("Download PGN") }}
81da2786 87 </button>
fd373b27 88 </div>
7d9e99bc 89 <my-move-list v-if="showMoves" :moves="moves" :cursor="cursor" @goto-move="gotoMove">
fd373b27 90 </my-move-list>
81da2786
BA
91 </div>
92 `,
1d184b4c 93 created: function() {
d44df0b0
BA
94 if (!!this.gameId)
95 this.loadGame();
96 else if (!!this.fen)
7d9e99bc 97 {
d44df0b0 98 this.vr = new VariantRules(this.fen);
7d9e99bc
BA
99 this.fenStart = this.fen;
100 }
fd373b27 101 // TODO: after game, archive in indexedDB
067c675b 102 // TODO: this events listener is central. Refactor ? How ?
d35f20e4 103 const socketMessageListener = msg => {
1d184b4c 104 const data = JSON.parse(msg.data);
edcd679a 105 let L = undefined;
1d184b4c
BA
106 switch (data.code)
107 {
1d184b4c 108 case "newmove": //..he played!
8d7e2786 109 this.play(data.move, (variant.name!="Dark" ? "animate" : null));
1d184b4c 110 break;
f3802fcd 111 case "pong": //received if we sent a ping (game still alive on our side)
56a683cd
BA
112 if (this.gameId != data.gameId)
113 break; //games IDs don't match: definitely over...
1d184b4c 114 this.oppConnected = true;
f3802fcd 115 // Send our "last state" informations to opponent
edcd679a 116 L = this.vr.moves.length;
a29d9d6b 117 this.conn.send(JSON.stringify({
56a683cd
BA
118 code: "lastate",
119 oppid: this.oppid,
120 gameId: this.gameId,
121 lastMove: (L>0?this.vr.moves[L-1]:undefined),
122 movesCount: L,
a29d9d6b 123 }));
1d184b4c 124 break;
56a683cd 125 case "lastate": //got opponent infos about last move
edcd679a 126 L = this.vr.moves.length;
56a683cd
BA
127 if (this.gameId != data.gameId)
128 break; //games IDs don't match: nothing we can do...
129 // OK, opponent still in game (which might be over)
edcd679a 130 if (this.score != "*")
a29d9d6b 131 {
56a683cd 132 // We finished the game (any result possible)
a29d9d6b 133 this.conn.send(JSON.stringify({
56a683cd
BA
134 code: "lastate",
135 oppid: data.oppid,
136 gameId: this.gameId,
137 score: this.score,
a29d9d6b
BA
138 }));
139 }
56a683cd
BA
140 else if (!!data.score) //opponent finished the game
141 this.endGame(data.score);
142 else if (data.movesCount < L)
a29d9d6b
BA
143 {
144 // We must tell last move to opponent
a29d9d6b 145 this.conn.send(JSON.stringify({
56a683cd
BA
146 code: "lastate",
147 oppid: this.oppid,
edcd679a 148 gameId: this.gameId,
56a683cd
BA
149 lastMove: this.vr.moves[L-1],
150 movesCount: L,
a29d9d6b
BA
151 }));
152 }
56a683cd 153 else if (data.movesCount > L) //just got last move from him
a29d9d6b 154 this.play(data.lastMove, "animate");
ecf44502 155 break;
1d184b4c 156 case "resign": //..you won!
dfb4afc1 157 this.endGame(this.mycolor=="w"?"1-0":"0-1");
1d184b4c 158 break;
f3802fcd 159 // TODO: also use (dis)connect info to count online players?
1d184b4c
BA
160 case "connect":
161 case "disconnect":
4f7723a1 162 if (this.mode=="human" && this.oppid == data.id)
1d184b4c 163 this.oppConnected = (data.code == "connect");
4f7723a1 164 if (this.oppConnected && this.score != "*")
3a609580
BA
165 {
166 // Send our name to the opponent, in case of he hasn't it
167 this.conn.send(JSON.stringify({
168 code:"myname", name:this.myname, oppid: this.oppid}));
169 }
1d184b4c
BA
170 break;
171 }
172 };
067c675b 173
d35f20e4 174 const socketCloseListener = () => {
d35f20e4
BA
175 this.conn.addEventListener('message', socketMessageListener);
176 this.conn.addEventListener('close', socketCloseListener);
177 };
d35f20e4
BA
178 this.conn.onmessage = socketMessageListener;
179 this.conn.onclose = socketCloseListener;
81da2786 180
067c675b 181 // Computer moves web worker logic: (TODO: also for observers in HH games)
8d7e2786 182 this.compWorker.postMessage(["scripts",variant.name]);
643479f8
BA
183 const self = this;
184 this.compWorker.onmessage = function(e) {
aa78cc74 185 let compMove = e.data;
78bab51e
BA
186 if (!compMove)
187 return; //may happen if MarseilleRules and subTurn==2 (TODO: a bit ugly...)
6e62b1c7
BA
188 if (!Array.isArray(compMove))
189 compMove = [compMove]; //to deal with MarseilleRules
190 // TODO: imperfect attempt to avoid ghost move:
191 compMove.forEach(m => { m.computer = true; });
643479f8
BA
192 // (first move) HACK: small delay to avoid selecting elements
193 // before they appear on page:
194 const delay = Math.max(500-(Date.now()-self.timeStart), 0);
195 setTimeout(() => {
8d7e2786 196 const animate = (variant.name!="Dark" ? "animate" : null);
aa78cc74 197 if (self.mode == "computer") //warning: mode could have changed!
5915f720 198 self.play(compMove[0], animate);
6e62b1c7
BA
199 if (compMove.length == 2)
200 setTimeout( () => {
201 if (self.mode == "computer")
5915f720 202 self.play(compMove[1], animate);
78bab51e 203 }, 750);
643479f8
BA
204 }, delay);
205 }
1d184b4c 206 },
d44df0b0 207 // this.conn est une prop, donnée depuis variant.js
fd373b27
BA
208 //dans variant.js (plutôt room.js) conn gère aussi les challenges
209 // Puis en webRTC, repenser tout ça.
81da2786 210 methods: {
d44df0b0
BA
211 translate: translate,
212 loadGame: function() {
59d58d7d
BA
213 const game = getGameFromStorage(this.gameId);
214 this.oppid = game.oppid; //opponent ID in case of running HH game
215 this.score = game.score;
216 this.mycolor = game.mycolor || "w";
217 this.fenStart = game.fenStart;
218 this.moves = game.moves;
219 this.cursor = game.moves.length;
220 this.lastMove = (game.moves.length > 0 ? game.moves[this.cursor-1] : null);
d44df0b0 221 },
fd373b27
BA
222 setEndgameMessage: function(score) {
223 let eogMessage = "Undefined";
224 switch (score)
225 {
226 case "1-0":
227 eogMessage = translations["White win"];
228 break;
229 case "0-1":
230 eogMessage = translations["Black win"];
231 break;
232 case "1/2":
233 eogMessage = translations["Draw"];
234 break;
235 case "?":
236 eogMessage = "Unfinished";
237 break;
238 }
239 this.endgameMessage = eogMessage;
240 },
01ca2adc 241 download: function() {
59d58d7d 242 const content = this.getPgn();
01ca2adc
BA
243 // Prepare and trigger download link
244 let downloadAnchor = document.getElementById("download");
245 downloadAnchor.setAttribute("download", "game.pgn");
edcd679a 246 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
01ca2adc
BA
247 downloadAnchor.click();
248 },
59d58d7d
BA
249 getPgn: function() {
250 let pgn = "";
251 pgn += '[Site "vchess.club"]\n';
252 const opponent = (this.mode=="human" ? "Anonymous" : "Computer");
253 pgn += '[Variant "' + variant.name + '"]\n';
254 pgn += '[Date "' + getDate(new Date()) + '"]\n';
255 const whiteName = ["human","computer"].includes(this.mode)
256 ? (this.mycolor=='w'?'Myself':opponent)
257 : "analyze";
258 const blackName = ["human","computer"].includes(this.mode)
259 ? (this.mycolor=='b'?'Myself':opponent)
260 : "analyze";
261 pgn += '[White "' + whiteName + '"]\n';
262 pgn += '[Black "' + blackName + '"]\n';
263 pgn += '[Fen "' + this.fenStart + '"]\n';
264 pgn += '[Result "' + this.score + '"]\n\n';
265 let counter = 1;
266 let i = 0;
267 while (i < this.moves.length)
268 {
269 pgn += (counter++) + ".";
270 for (let color of ["w","b"])
271 {
272 let move = "";
273 while (i < this.moves.length && this.moves[i].color == color)
274 move += this.moves[i++].notation[0] + ",";
275 move = move.slice(0,-1); //remove last comma
276 pgn += move + (i < this.moves.length-1 ? " " : "");
277 }
278 }
279 return pgn + "\n";
280 },
fd373b27
BA
281 showScoreMsg: function(score) {
282 this.setEndgameMessage(score);
ecf44502 283 let modalBox = document.getElementById("modal-eog");
186516b8 284 modalBox.checked = true;
1a788978
BA
285 setTimeout(() => { modalBox.checked = false; }, 2000);
286 },
287 endGame: function(score) {
288 this.score = score;
56a683cd
BA
289 if (["human","computer"].includes(this.mode))
290 {
291 const prefix = (this.mode=="computer" ? "comp-" : "");
292 localStorage.setItem(prefix+"score", score);
293 }
fd373b27 294 this.showScoreMsg(score);
3a609580
BA
295 if (this.mode == "human" && this.oppConnected)
296 {
297 // Send our nickname to opponent
298 this.conn.send(JSON.stringify({
299 code:"myname", name:this.myname, oppid:this.oppid}));
300 }
fd373b27
BA
301 // TODO: what about cursor ?
302 //this.cursor = this.vr.moves.length; //to navigate in finished game
1d184b4c 303 },
067c675b
BA
304 resign: function(e) {
305 this.getRidOfTooltip(e.currentTarget);
306 if (this.mode == "human" && this.oppConnected)
307 {
308 try {
309 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
310 } catch (INVALID_STATE_ERR) {
311 return; //socket is not ready (and not yet reconnected)
312 }
313 }
314 this.endGame(this.mycolor=="w"?"0-1":"1-0");
315 },
1d184b4c 316 playComputerMove: function() {
643479f8
BA
317 this.timeStart = Date.now();
318 this.compWorker.postMessage(["askmove"]);
1d184b4c 319 },
fd373b27
BA
320 animateMove: function(move) {
321 let startSquare = document.getElementById(this.getSquareId(move.start));
322 let endSquare = document.getElementById(this.getSquareId(move.end));
323 let rectStart = startSquare.getBoundingClientRect();
324 let rectEnd = endSquare.getBoundingClientRect();
325 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
326 let movingPiece =
327 document.querySelector("#" + this.getSquareId(move.start) + " > img.piece");
328 // HACK for animation (with positive translate, image slides "under background")
329 // Possible improvement: just alter squares on the piece's way...
330 squares = document.getElementsByClassName("board");
331 for (let i=0; i<squares.length; i++)
332 {
333 let square = squares.item(i);
334 if (square.id != this.getSquareId(move.start))
335 square.style.zIndex = "-1";
336 }
337 movingPiece.style.transform = "translate(" + translation.x + "px," +
338 translation.y + "px)";
339 movingPiece.style.transitionDuration = "0.2s";
340 movingPiece.style.zIndex = "3000";
341 setTimeout( () => {
342 for (let i=0; i<squares.length; i++)
343 squares.item(i).style.zIndex = "auto";
344 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
345 this.play(move); //TODO: plutôt envoyer message "please play"
346 }, 250);
347 },
348 play: function(move, programmatic) {
7d9e99bc
BA
349 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
350 if (this.mode != "analyze" && this.cursor < this.moves.length-1)
351 return;
352 let navigate = !move;
353 if (navigate)
354 {
355 if (this.cursor == this.moves.length)
356 return; //no more moves
357 move = this.moves[this.cursor];
358 }
fd373b27
BA
359 if (!!programmatic) //computer or human opponent
360 return this.animateMove(move);
361 // Not programmatic, or animation is over
362 if (!move.notation)
363 move.notation = this.vr.getNotation(move);
7d9e99bc
BA
364 if (!move.color)
365 move.color = this.vr.turn;
fd373b27 366 this.vr.play(move);
7d9e99bc 367 this.cursor++;
59d58d7d 368 this.lastMove = move;
fd373b27
BA
369 if (!move.fen)
370 move.fen = this.vr.getFen();
371 if (this.sound == 2)
372 new Audio("/sounds/move.mp3").play().catch(err => {});
373 if (this.mode == "human")
374 {
375 updateStorage(move); //after our moves and opponent moves
376 if (this.vr.turn == this.userColor)
377 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
378 }
379 else if (this.mode == "computer")
380 {
381 // Send the move to web worker (including his own moves)
382 this.compWorker.postMessage(["newmove",move]);
383 }
7d9e99bc 384 if (!navigate && (this.score == "*" || this.mode == "analyze"))
fd373b27 385 {
7d9e99bc
BA
386 // Stack move on movesList at current cursor
387 if (this.cursor == this.moves.length)
388 this.moves.push(move);
389 else
390 this.moves = this.moves.slice(0,this.cursor-1).concat([move]);
fd373b27
BA
391 }
392 // Is opponent in check?
393 this.incheck = this.vr.getCheckSquares(this.vr.turn);
394 const score = this.vr.getCurrentScore();
395 if (score != "*")
396 {
397 if (["human","computer"].includes(this.mode))
398 this.endGame(score);
399 else //just show score on screen (allow undo)
400 this.showScoreMsg(score);
401 // TODO: notify end of game (give score)
402 }
403 else if (this.mode == "computer" && this.vr.turn != this.userColor)
404 this.playComputerMove();
59d58d7d 405 // https://vuejs.org/v2/guide/list.html#Caveats (also for undo)
7d9e99bc
BA
406 if (navigate)
407 this.$children[0].$forceUpdate(); //TODO!?
fd373b27
BA
408 },
409 undo: function(move) {
7d9e99bc
BA
410 let navigate = !move;
411 if (navigate)
412 {
413 if (this.cursor == 0)
414 return; //no more moves
415 move = this.moves[this.cursor-1];
416 }
fd373b27 417 this.vr.undo(move);
7d9e99bc 418 this.cursor--;
59d58d7d 419 this.lastMove = (this.cursor > 0 ? this.moves[this.cursor-1] : undefined);
7d9e99bc
BA
420 if (navigate)
421 this.$children[0].$forceUpdate(); //TODO!?
fd373b27
BA
422 if (this.sound == 2)
423 new Audio("/sounds/undo.mp3").play().catch(err => {});
424 this.incheck = this.vr.getCheckSquares(this.vr.turn);
7d9e99bc 425 if (!navigate && this.mode == "analyze")
fd373b27 426 this.moves.pop();
7d9e99bc
BA
427 if (navigate)
428 this.$forceUpdate(); //TODO!?
429 },
430 gotoMove: function(index) {
431 this.vr = new VariantRules(this.moves[index].fen);
432 this.cursor = index+1;
59d58d7d 433 this.lastMove = this.moves[index];
7d9e99bc
BA
434 },
435 gotoBegin: function() {
436 this.vr = new VariantRules(this.fenStart);
437 this.cursor = 0;
59d58d7d 438 this.lastMove = null;
7d9e99bc
BA
439 },
440 gotoEnd: function() {
441 this.gotoMove(this.moves.length-1);
59d58d7d 442 this.lastMove = this.moves[this.moves.length-1];
7d9e99bc
BA
443 },
444 flip: function() {
445 this.orientation = V.GetNextCol(this.orientation);
fd373b27 446 },
1d184b4c
BA
447 },
448})
067c675b
BA
449//TODO: confirm dialog with "opponent offers draw", avec possible bouton "prevent future offers" + bouton "proposer nulle"
450//+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
451//comme sur lichess
fd373b27 452//TODO: quand partie terminée (ci-dessus) passer partie dans indexedDB