Debugging problems page; TODO: hash navigation is wrong
[vchess.git] / public / javascripts / components / game.js
1 // Game logic on a variant page: 3 modes, analyze, computer or human
2 // TODO: envoyer juste "light move", sans FEN ni notation ...etc
3 // TODO: if I'm an observer and player(s) disconnect/reconnect, how to find me ?
4 // onClick :: ask full game to remote player, and register as an observer in game
5 // (use gameId to communicate)
6 // on landing on game :: if gameId not found locally, check remotely
7 // ==> il manque un param dans game : "remoteId"
8 Vue.component('my-game', {
9 // gameId: to find the game in storage (assumption: it exists)
10 // fen: to start from a FEN without identifiers (analyze mode)
11 // subMode: "auto" (game comp vs comp) or "corr" (correspondance game),
12 // or "examine" (after human game: TODO)
13 props: ["conn","gameId","fen","mode","subMode","allowChat","allowMovelist",
14 "queryHash","settings"],
15 data: function() {
16 return {
17 // Web worker to play computer moves without freezing interface:
18 compWorker: new Worker('/javascripts/playCompMove.js'),
19 timeStart: undefined, //time when computer starts thinking
20 vr: null, //VariantRules object, describing the game state + rules
21 endgameMessage: "",
22 orientation: "w",
23 lockCompThink: false, //used to avoid some ghost moves
24 myname: user.name, //may be anonymous (thus no name)
25 opponents: {}, //filled later (potentially 2 or 3 opponents)
26 drawOfferSent: false, //did I just ask for draw?
27 people: {}, //observers
28 score: "*", //'*' means 'unfinished'
29 // userColor: given by gameId, or fen in problems mode (if no game Id)...
30 mycolor: "w",
31 fenStart: "",
32 moves: [], //TODO: initialize if gameId is defined...
33 cursor: -1, //index of the move just played
34 lastMove: null,
35 };
36 },
37 watch: {
38 fen: function() {
39 // (Security) No effect if a computer move is in progress:
40 if (this.mode == "computer" && this.lockCompThink)
41 return this.$emit("computer-think");
42 this.newGameFromFen();
43 },
44 gameId: function() {
45 this.loadGame();
46 },
47 queryHash: function(newQhash) {
48 // New query hash = "id=42"; get 42 as gameId
49 this.gameId = parseInt(newQhash.substr(2));
50 this.loadGame();
51 },
52 },
53 computed: {
54 showChat: function() {
55 return this.allowChat && this.mode=='human' && this.score != '*';
56 },
57 showMoves: function() {
58 return true;
59 return this.allowMovelist && window.innerWidth >= 768;
60 },
61 showFen: function() {
62 return variant.name != "Dark" || this.score != "*";
63 },
64 },
65 // Modal end of game, and then sub-components
66 template: `
67 <div class="col-sm-12 col-md-10 col-md-offset-1 col-lg-8 col-lg-offset-2">
68 <input id="modal-eog" type="checkbox" class="modal"/>
69 <div role="dialog" aria-labelledby="eogMessage">
70 <div class="card smallpad small-modal text-center">
71 <label for="modal-eog" class="modal-close">
72 </label>
73 <h3 id="eogMessage" class="section">
74 {{ endgameMessage }}
75 </h3>
76 </div>
77 </div>
78 <my-chat v-if="showChat" :conn="conn" :myname="myname"
79 :opponents="opponents" :people="people">
80 </my-chat>
81 <my-board v-bind:vr="vr" :last-move="lastMove" :mode="mode"
82 :orientation="orientation" :user-color="mycolor" :settings="settings"
83 @play-move="play">
84 </my-board>
85 <div class="button-group">
86 <button @click="() => play()">Play</button>
87 <button @click="() => undo()">Undo</button>
88 <button @click="flip">Flip</button>
89 <button @click="gotoBegin">GotoBegin</button>
90 <button @click="gotoEnd">GotoEnd</button>
91 </div>
92 <div v-if="mode=='human'" class="button-group">
93 <button @click="offerDraw">Draw</button>
94 <button @click="abortGame">Abort</button>
95 <button @click="resign">Resign</button>
96 </div>
97 <div v-if="mode=='human' && subMode=='corr'">
98 <textarea v-show="score=='*' && vr.turn==mycolor" v-model="corrMsg">
99 </textarea>
100 <div v-show="cursor>=0">
101 {{ moves[cursor].message }}
102 </div>
103 </div>
104 <div v-if="showFen && !!vr" id="fen-div" class="section-content">
105 <p id="fen-string" class="text-center">
106 {{ vr.getFen() }}
107 </p>
108 </div>
109 <div id="pgn-div" class="section-content">
110 <a id="download" href="#">
111 </a>
112 <div class="button-group">
113 <button id="downloadBtn" @click="download">
114 {{ translate("Download PGN") }}
115 </button>
116 <button>Import game</button>
117 </div>
118 </div>
119 <my-move-list v-if="showMoves" :moves="moves" :cursor="cursor" @goto-move="gotoMove">
120 </my-move-list>
121 </div>
122 `,
123 created: function() {
124 if (!!this.gameId)
125 this.loadGame();
126 else if (!!this.fen)
127 {
128 this.vr = new VariantRules(this.fen);
129 this.fenStart = this.fen;
130 }
131 // TODO: if I'm one of the players in game, then:
132 // Send ping to server (answer pong if opponent is connected)
133 if (true && !!this.conn)
134 {
135 this.conn.onopen = () => {
136 this.conn.send(JSON.stringify({
137 code:"ping",oppid:this.oppid,gameId:this.gameId}));
138 };
139 }
140 // TODO: also handle "draw accepted" (use opponents array?)
141 // --> must give this info also when sending lastState...
142 // and, if all players agree then OK draw (end game ...etc)
143 const socketMessageListener = msg => {
144 const data = JSON.parse(msg.data);
145 let L = undefined;
146 switch (data.code)
147 {
148 case "newmove": //..he played!
149 this.play(data.move, variant.name!="Dark" ? "animate" : null);
150 break;
151 case "pong": //received if we sent a ping (game still alive on our side)
152 if (this.gameId != data.gameId)
153 break; //games IDs don't match: definitely over...
154 this.oppConnected = true;
155 // Send our "last state" informations to opponent(s)
156 L = this.vr.moves.length;
157 Object.keys(this.opponents).forEach(oid => {
158 this.conn.send(JSON.stringify({
159 code: "lastate",
160 oppid: oid,
161 gameId: this.gameId,
162 lastMove: (L>0?this.vr.moves[L-1]:undefined),
163 movesCount: L,
164 }));
165 });
166 break;
167 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves (not just one)
168 case "lastate": //got opponent infos about last move
169 L = this.vr.moves.length;
170 if (this.gameId != data.gameId)
171 break; //games IDs don't match: nothing we can do...
172 // OK, opponent still in game (which might be over)
173 if (this.score != "*")
174 {
175 // We finished the game (any result possible)
176 this.conn.send(JSON.stringify({
177 code: "lastate",
178 oppid: data.oppid,
179 gameId: this.gameId,
180 score: this.score,
181 }));
182 }
183 else if (!!data.score) //opponent finished the game
184 this.endGame(data.score);
185 else if (data.movesCount < L)
186 {
187 // We must tell last move to opponent
188 this.conn.send(JSON.stringify({
189 code: "lastate",
190 oppid: this.opponent.id,
191 gameId: this.gameId,
192 lastMove: this.vr.moves[L-1],
193 movesCount: L,
194 }));
195 }
196 else if (data.movesCount > L) //just got last move from him
197 this.play(data.lastMove, "animate");
198 break;
199 case "resign": //..you won!
200 this.endGame(this.mycolor=="w"?"1-0":"0-1");
201 break;
202 // TODO: also use (dis)connect info to count online players?
203 case "connect":
204 case "disconnect":
205 if (this.mode=="human")
206 {
207 const online = (data.code == "connect");
208 // If this is an opponent ?
209 if (!!this.opponents[data.id])
210 this.opponents[data.id].online = online;
211 else
212 {
213 // Or an observer ?
214 if (!online)
215 delete this.people[data.id];
216 else
217 this.people[data.id] = data.name;
218 }
219 }
220 break;
221 }
222 };
223 const socketCloseListener = () => {
224 this.conn.addEventListener('message', socketMessageListener);
225 this.conn.addEventListener('close', socketCloseListener);
226 };
227 if (!!this.conn)
228 {
229 this.conn.onmessage = socketMessageListener;
230 this.conn.onclose = socketCloseListener;
231 }
232 // Computer moves web worker logic: (TODO: also for observers in HH games ?)
233 this.compWorker.postMessage(["scripts",variant.name]);
234 this.compWorker.onmessage = e => {
235 this.lockCompThink = true; //to avoid some ghost moves
236 let compMove = e.data;
237 if (!Array.isArray(compMove))
238 compMove = [compMove]; //to deal with MarseilleRules
239 // Small delay for the bot to appear "more human"
240 const delay = Math.max(500-(Date.now()-this.timeStart), 0);
241 setTimeout(() => {
242 const animate = variant.name != "Dark";
243 this.play(compMove[0], animate);
244 if (compMove.length == 2)
245 setTimeout( () => { this.play(compMove[1], animate); }, 750);
246 else //250 == length of animation (TODO: should be a constant somewhere)
247 setTimeout( () => this.lockCompThink = false, 250);
248 }, delay);
249 }
250 },
251 // dans variant.js (plutôt room.js) conn gère aussi les challenges
252 // et les chats dans chat.js. Puis en webRTC, repenser tout ça.
253 methods: {
254 offerDraw: function() {
255 if (!confirm("Offer draw?"))
256 return;
257 // Stay in "draw offer sent" state until next move is played
258 this.drawOfferSent = true;
259 if (this.subMode == "corr")
260 {
261 // TODO: set drawOffer on in game (how ?)
262 }
263 else //live game
264 {
265 this.opponents.forEach(o => {
266 if (!!o.online)
267 {
268 try {
269 this.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
270 } catch (INVALID_STATE_ERR) {
271 return;
272 }
273 }
274 });
275 }
276 },
277 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
278 receiveDrawOffer: function() {
279 //if (...)
280 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
281 // if accept: send message "draw"
282 },
283 abortGame: function() {
284 if (!confirm("Abort the game?"))
285 return;
286 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
287 //send message: "gameOver" avec score "?"
288 },
289 resign: function(e) {
290 if (!confirm("Resign the game?"))
291 return;
292 if (this.mode == "human" && this.oppConnected(this.oppid))
293 {
294 try {
295 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
296 } catch (INVALID_STATE_ERR) {
297 return;
298 }
299 }
300 this.endGame(this.mycolor=="w"?"0-1":"1-0");
301 },
302 translate: translate,
303 newGameFromFen: function() {
304 this.vr = new VariantRules(this.fen);
305 this.moves = [];
306 this.cursor = -1;
307 this.fenStart = this.fen;
308 this.score = "*";
309 if (this.mode == "analyze")
310 {
311 this.mycolor = V.ParseFen(this.fen).turn;
312 this.orientation = this.mycolor;
313 }
314 else if (this.mode == "computer") //only other alternative (HH with gameId)
315 {
316 this.mycolor = (Math.random() < 0.5 ? "w" : "b");
317 this.orientation = this.mycolor;
318 this.compWorker.postMessage(["init",this.fen]);
319 if (this.mycolor != "w" || this.subMode == "auto")
320 this.playComputerMove();
321 }
322 },
323 loadGame: function() {
324 // TODO: ask game to remote peer if this.remoteId is set
325 // (or just if game not found locally)
326 // NOTE: if it's a corr game, ask it from server
327 const game = getGameFromStorage(this.gameId);
328 this.opponent.id = game.oppid; //opponent ID in case of running HH game
329 this.opponent.name = game.oppname; //maye be blank (if anonymous)
330 this.score = game.score;
331 this.mycolor = game.mycolor;
332 this.fenStart = game.fenStart;
333 this.moves = game.moves;
334 this.cursor = game.moves.length-1;
335 this.lastMove = (game.moves.length > 0 ? game.moves[this.cursor] : null);
336 },
337 setEndgameMessage: function(score) {
338 let eogMessage = "Undefined";
339 switch (score)
340 {
341 case "1-0":
342 eogMessage = translations["White win"];
343 break;
344 case "0-1":
345 eogMessage = translations["Black win"];
346 break;
347 case "1/2":
348 eogMessage = translations["Draw"];
349 break;
350 case "?":
351 eogMessage = "Unfinished";
352 break;
353 }
354 this.endgameMessage = eogMessage;
355 },
356 download: function() {
357 const content = this.getPgn();
358 // Prepare and trigger download link
359 let downloadAnchor = document.getElementById("download");
360 downloadAnchor.setAttribute("download", "game.pgn");
361 downloadAnchor.href = "data:text/plain;charset=utf-8," + encodeURIComponent(content);
362 downloadAnchor.click();
363 },
364 getPgn: function() {
365 let pgn = "";
366 pgn += '[Site "vchess.club"]\n';
367 const opponent = (this.mode=="human" ? "Anonymous" : "Computer");
368 pgn += '[Variant "' + variant.name + '"]\n';
369 pgn += '[Date "' + getDate(new Date()) + '"]\n';
370 const whiteName = ["human","computer"].includes(this.mode)
371 ? (this.mycolor=='w'?'Myself':opponent)
372 : "analyze";
373 const blackName = ["human","computer"].includes(this.mode)
374 ? (this.mycolor=='b'?'Myself':opponent)
375 : "analyze";
376 pgn += '[White "' + whiteName + '"]\n';
377 pgn += '[Black "' + blackName + '"]\n';
378 pgn += '[Fen "' + this.fenStart + '"]\n';
379 pgn += '[Result "' + this.score + '"]\n\n';
380 let counter = 1;
381 let i = 0;
382 while (i < this.moves.length)
383 {
384 pgn += (counter++) + ".";
385 for (let color of ["w","b"])
386 {
387 let move = "";
388 while (i < this.moves.length && this.moves[i].color == color)
389 move += this.moves[i++].notation[0] + ",";
390 move = move.slice(0,-1); //remove last comma
391 pgn += move + (i < this.moves.length-1 ? " " : "");
392 }
393 }
394 return pgn + "\n";
395 },
396 showScoreMsg: function(score) {
397 this.setEndgameMessage(score);
398 let modalBox = document.getElementById("modal-eog");
399 modalBox.checked = true;
400 setTimeout(() => { modalBox.checked = false; }, 2000);
401 },
402 endGame: function(score) {
403 this.score = score;
404 this.showScoreMsg(score);
405 if (this.mode == "human")
406 localStorage["score"] = score;
407 this.$emit("game-over");
408 },
409 oppConnected: function(uid) {
410 return this.opponents.any(o => o.id == uidi && o.online);
411 },
412 playComputerMove: function() {
413 this.timeStart = Date.now();
414 this.compWorker.postMessage(["askmove"]);
415 },
416 animateMove: function(move) {
417 let startSquare = document.getElementById(getSquareId(move.start));
418 let endSquare = document.getElementById(getSquareId(move.end));
419 let rectStart = startSquare.getBoundingClientRect();
420 let rectEnd = endSquare.getBoundingClientRect();
421 let translation = {x:rectEnd.x-rectStart.x, y:rectEnd.y-rectStart.y};
422 let movingPiece =
423 document.querySelector("#" + getSquareId(move.start) + " > img.piece");
424 // HACK for animation (with positive translate, image slides "under background")
425 // Possible improvement: just alter squares on the piece's way...
426 squares = document.getElementsByClassName("board");
427 for (let i=0; i<squares.length; i++)
428 {
429 let square = squares.item(i);
430 if (square.id != getSquareId(move.start))
431 square.style.zIndex = "-1";
432 }
433 movingPiece.style.transform = "translate(" + translation.x + "px," +
434 translation.y + "px)";
435 movingPiece.style.transitionDuration = "0.2s";
436 movingPiece.style.zIndex = "3000";
437 setTimeout( () => {
438 for (let i=0; i<squares.length; i++)
439 squares.item(i).style.zIndex = "auto";
440 movingPiece.style = {}; //required e.g. for 0-0 with KR swap
441 this.play(move);
442 }, 250);
443 },
444 play: function(move, programmatic) {
445 let navigate = !move;
446 // Forbid playing outside analyze mode when cursor isn't at moves.length-1
447 // (except if we receive opponent's move, human or computer)
448 if (!navigate && this.mode != "analyze" && !programmatic
449 && this.cursor < this.moves.length-1)
450 {
451 return;
452 }
453 if (navigate)
454 {
455 if (this.cursor == this.moves.length-1)
456 return; //no more moves
457 move = this.moves[this.cursor+1];
458 }
459 if (!!programmatic) //computer or (remote) human opponent
460 {
461 if (this.cursor < this.moves.length-1)
462 this.gotoEnd(); //required to play the move
463 return this.animateMove(move);
464 }
465 // Not programmatic, or animation is over
466 if (this.mode == "human" && this.subMode == "corr" && this.mycolor == this.vr.turn)
467 {
468 // TODO: show confirm box "validate move ?"
469 }
470 if (!move.notation)
471 move.notation = this.vr.getNotation(move);
472 if (!move.color)
473 move.color = this.vr.turn;
474 this.vr.play(move);
475 this.cursor++;
476 this.lastMove = move;
477 if (!move.fen)
478 move.fen = this.vr.getFen();
479 if (this.settings.sound == 2)
480 new Audio("/sounds/move.mp3").play().catch(err => {});
481 if (this.mode == "human")
482 {
483 updateStorage(move); //after our moves and opponent moves
484 if (this.vr.turn == this.mycolor)
485 this.conn.send(JSON.stringify({code:"newmove", move:move, oppid:this.oppid}));
486 }
487 else if (this.mode == "computer")
488 {
489 // Send the move to web worker (including his own moves)
490 this.compWorker.postMessage(["newmove",move]);
491 }
492 if (!navigate && (this.score == "*" || this.mode == "analyze"))
493 {
494 // Stack move on movesList at current cursor
495 if (this.cursor == this.moves.length)
496 this.moves.push(move);
497 else
498 this.moves = this.moves.slice(0,this.cursor-1).concat([move]);
499 }
500 // Is opponent in check?
501 this.incheck = this.vr.getCheckSquares(this.vr.turn);
502 const score = this.vr.getCurrentScore();
503 if (score != "*")
504 {
505 if (["human","computer"].includes(this.mode))
506 this.endGame(score);
507 else //just show score on screen (allow undo)
508 this.showScoreMsg(score);
509 }
510 // subTurn condition for Marseille (and Avalanche) rules
511 else if ((this.mode == "computer" && (!this.vr.subTurn || this.vr.subTurn <= 1))
512 && (this.subMode == "auto" || this.vr.turn != this.mycolor))
513 {
514 this.playComputerMove();
515 }
516 // https://vuejs.org/v2/guide/list.html#Caveats (also for undo)
517 if (navigate)
518 this.$children[0].$forceUpdate(); //TODO!?
519 },
520 undo: function(move) {
521 let navigate = !move;
522 if (navigate)
523 {
524 if (this.cursor < 0)
525 return; //no more moves
526 move = this.moves[this.cursor];
527 }
528 this.vr.undo(move);
529 this.cursor--;
530 this.lastMove = (this.cursor >= 0 ? this.moves[this.cursor] : undefined);
531 if (this.settings.sound == 2)
532 new Audio("/sounds/undo.mp3").play().catch(err => {});
533 this.incheck = this.vr.getCheckSquares(this.vr.turn);
534 if (navigate)
535 this.$children[0].$forceUpdate(); //TODO!?
536 else if (this.mode == "analyze") //TODO: can this happen?
537 this.moves.pop();
538 },
539 gotoMove: function(index) {
540 this.vr = new VariantRules(this.moves[index].fen);
541 this.cursor = index;
542 this.lastMove = this.moves[index];
543 },
544 gotoBegin: function() {
545 this.vr = new VariantRules(this.fenStart);
546 this.cursor = -1;
547 this.lastMove = null;
548 },
549 gotoEnd: function() {
550 this.gotoMove(this.moves.length-1);
551 },
552 flip: function() {
553 this.orientation = V.GetNextCol(this.orientation);
554 },
555 },
556 })