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