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