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