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")
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
30 button#downloadBtn(@click="download") {{ st.tr["Download PGN"] }}
32 //MoveList(v-if="showMoves"
33 :moves="moves" :cursor="cursor" @goto-move="gotoMove")
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";
50 import { getSquareId } from "@/utils/squareId";
52 import Worker from 'worker-loader!@/playCompMove';
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"],
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
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)...
82 moves: [], //all moves played in current game
83 cursor: -1, //index of the move just played
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");
95 variant: function(newVar) {
99 showMoves: function() {
101 //return window.innerWidth >= 768;
103 showFen: function() {
104 return this.variant.name != "Dark" || this.score != "*";
107 // Modal end of game, and then sub-components
108 created: function() {
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)
115 this.conn.onopen = () => {
116 this.conn.send(JSON.stringify({
117 code:"ping",oppid:this.oppid,gameId:this.gameRef.id}));
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);
128 case "newmove": //..he played!
129 this.play(data.move, this.variant.name!="Dark" ? "animate" : null);
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({
141 gameId: this.gameRef.id,
142 lastMove: (L>0?this.vr.moves[L-1]:undefined),
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 != "*")
155 // We finished the game (any result possible)
156 this.conn.send(JSON.stringify({
159 gameId: this.gameRef.id,
163 else if (!!data.score) //opponent finished the game
164 this.endGame(data.score);
165 else if (data.movesCount < L)
167 // We must tell last move to opponent
168 this.conn.send(JSON.stringify({
170 oppid: this.opponent.id,
171 gameId: this.gameRef.id,
172 lastMove: this.vr.moves[L-1],
176 else if (data.movesCount > L) //just got last move from him
177 this.play(data.lastMove, "animate");
179 case "resign": //..you won!
180 this.endGame(this.mycolor=="w"?"1-0":"0-1");
182 // TODO: also use (dis)connect info to count online players?
185 if (this.mode=="human")
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;
195 delete this.people[data.id];
197 this.people[data.id] = data.name;
203 const socketCloseListener = () => {
204 this.conn.addEventListener('message', socketMessageListener);
205 this.conn.addEventListener('close', socketCloseListener);
209 this.conn.onmessage = socketMessageListener;
210 this.conn.onclose = socketCloseListener;
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);
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);
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.
234 offerDraw: function() {
235 if (!confirm("Offer draw?"))
237 // Stay in "draw offer sent" state until next move is played
238 this.drawOfferSent = true;
239 if (this.subMode == "corr")
241 // TODO: set drawOffer on in game (how ?)
245 this.opponents.forEach(o => {
249 this.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
250 } catch (INVALID_STATE_ERR) {
257 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
258 receiveDrawOffer: function() {
260 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
261 // if accept: send message "draw"
263 abortGame: function() {
264 if (!confirm("Abort the game?"))
266 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
267 //send message: "gameOver" avec score "?"
269 resign: function(e) {
270 if (!confirm("Resign the game?"))
272 if (this.mode == "human" && this.oppConnected(this.oppid))
275 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
276 } catch (INVALID_STATE_ERR) {
280 this.endGame(this.mycolor=="w"?"0-1":"1-0");
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);
289 this.loadGame(this.gidOrFen);
291 newGameFromFen: function(fen) {
292 this.vr = new V(fen);
297 if (this.mode == "analyze")
299 this.mycolor = V.ParseFen(fen).turn;
300 this.orientation = this.mycolor;
302 else if (this.mode == "computer") //only other alternative (HH with gameId)
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();
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);
325 setEndgameMessage: function(score) {
326 let eogMessage = "Undefined";
330 eogMessage = translations["White win"];
333 eogMessage = translations["Black win"];
336 eogMessage = translations["Draw"];
339 eogMessage = "Unfinished";
342 this.endgameMessage = eogMessage;
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();
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)
361 const blackName = ["human","computer"].includes(this.mode)
362 ? (this.mycolor=='b'?'Myself':opponent)
364 pgn += '[White "' + whiteName + '"]\n';
365 pgn += '[Black "' + blackName + '"]\n';
366 pgn += '[Fen "' + this.fenStart + '"]\n';
367 pgn += '[Result "' + this.score + '"]\n\n';
370 while (i < this.moves.length)
372 pgn += (counter++) + ".";
373 for (let color of ["w","b"])
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 ? " " : "");
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);
390 endGame: function(score) {
392 this.showScoreMsg(score);
393 if (this.mode == "human")
394 localStorage["score"] = score;
395 this.$emit("game-over");
397 oppConnected: function(uid) {
398 return this.opponents.any(o => o.id == uidi && o.online);
400 playComputerMove: function() {
401 this.timeStart = Date.now();
402 this.compWorker.postMessage(["askmove"]);
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};
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++)
417 let square = squares.item(i);
418 if (square.id != getSquareId(move.start))
419 square.style.zIndex = "-1";
421 movingPiece.style.transform = "translate(" + translation.x + "px," +
422 translation.y + "px)";
423 movingPiece.style.transitionDuration = "0.2s";
424 movingPiece.style.zIndex = "3000";
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
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)
443 if (this.cursor == this.moves.length-1)
444 return; //no more moves
445 move = this.moves[this.cursor+1];
447 if (!!programmatic) //computer or (remote) human opponent
449 if (this.cursor < this.moves.length-1)
450 this.gotoEnd(); //required to play the move
451 return this.animateMove(move);
453 // Not programmatic, or animation is over
454 if (this.mode == "human" && this.subMode == "corr" && this.mycolor == this.vr.turn)
456 // TODO: show confirm box "validate move ?"
459 move.notation = this.vr.getNotation(move);
461 move.color = this.vr.turn;
464 this.lastMove = move;
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")
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}));
475 else if (this.mode == "computer")
477 // Send the move to web worker (including his own moves)
478 this.compWorker.postMessage(["newmove",move]);
480 if (!navigate && (this.score == "*" || this.mode == "analyze"))
482 // Stack move on movesList at current cursor
483 if (this.cursor == this.moves.length)
484 this.moves.push(move);
486 this.moves = this.moves.slice(0,this.cursor).concat([move]);
488 // Is opponent in check?
489 this.incheck = this.vr.getCheckSquares(this.vr.turn);
490 const score = this.vr.getCurrentScore();
493 if (["human","computer"].includes(this.mode))
495 else //just show score on screen (allow undo)
496 this.showScoreMsg(score);
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))
502 this.playComputerMove();
504 // https://vuejs.org/v2/guide/list.html#Caveats (also for undo)
506 this.$children[0].$forceUpdate(); //TODO!?
508 undo: function(move) {
509 let navigate = !move;
513 return; //no more moves
514 move = this.moves[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);
523 this.$children[0].$forceUpdate(); //TODO!?
524 else if (this.mode == "analyze") //TODO: can this happen?
527 gotoMove: function(index) {
528 this.vr = new V(this.moves[index].fen);
530 this.lastMove = this.moves[index];
532 gotoBegin: function() {
533 this.vr = new V(this.fenStart);
535 this.lastMove = null;
537 gotoEnd: function() {
538 this.gotoMove(this.moves.length-1);
541 this.orientation = V.GetNextCol(this.orientation);