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