5 @click="resetChatColor()"
9 data-checkbox="modalChat"
12 label.modal-close(for="modalChat")
14 span {{ Object.keys(people).length + " " + st.tr["participant(s):"] }}
16 v-for="p in Object.values(people)"
20 span.anonymous(v-if="Object.values(people).some(p => !p.name && p.id === 0)")
23 :players="game.players"
24 :pastChats="game.chats"
27 @chatcleared="clearChat"
30 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
31 span.variant-cadence {{ game.cadence }}
32 span.variant-name {{ game.vname }}
33 button#chatBtn(onClick="window.doClick('modalChat')") Chat
34 #actions(v-if="game.score=='*'")
37 :class="{['draw-' + drawOffer]: true}"
44 | {{ st.tr["Abort"] }}
49 | {{ st.tr["Resign"] }}
52 span.name(:class="{connected: isConnected(0)}")
53 | {{ game.players[0].name || "@nonymous" }}
54 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
56 span.name(:class="{connected: isConnected(1)}")
57 | {{ game.players[1].name || "@nonymous" }}
58 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
62 @newmove="processMove"
68 import BaseGame from "@/components/BaseGame.vue";
69 import Chat from "@/components/Chat.vue";
70 import { store } from "@/store";
71 import { GameStorage } from "@/utils/gameStorage";
72 import { ppt } from "@/utils/datetime";
73 import { ajax } from "@/utils/ajax";
74 import { extractTime } from "@/utils/timeControl";
75 import { getRandString } from "@/utils/alea";
76 import { processModalClick } from "@/utils/modalClick";
77 import { getFullNotation } from "@/utils/notation";
78 import { playMove, getFilteredMove } from "@/utils/playUndo";
79 import { getScoreMessage } from "@/utils/scoring";
80 import { ArrayFun } from "@/utils/array";
81 import params from "@/parameters";
88 // gameRef: to find the game in (potentially remote) storage
93 // rid = remote (socket) ID
99 players: [{ name: "" }, { name: "" }],
103 virtualClocks: [0, 0], //initialized with true game.clocks
104 vr: null, //"variant rules" object initialized from FEN
106 people: {}, //players + observers
107 onMygames: [], //opponents (or me) on "MyGames" page
108 lastate: undefined, //used if opponent send lastate before game is ready
109 repeat: {}, //detect position repetition
112 roomInitialized: false,
113 // If newmove has wrong index: ask fullgame again:
114 fullGamerequested: false,
115 // If asklastate got no reply, ask again:
117 // If newmove got no pingback, send again:
118 opponentGotMove: false,
120 // Related to (killing of) self multi-connects:
126 $route: function(to) {
127 this.gameRef.id = to.params["id"];
128 this.gameRef.rid = to.query["rid"];
132 // NOTE: some redundant code with Hall.vue (mostly related to people array)
133 created: function() {
134 // Always add myself to players' list
135 const my = this.st.user;
136 this.$set(this.people, my.sid, { id: my.id, name: my.name });
137 this.gameRef.id = this.$route.params["id"];
138 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
139 // Initialize connection
140 this.connexionString =
147 encodeURIComponent(this.$route.path);
148 this.conn = new WebSocket(this.connexionString);
149 this.conn.onmessage = this.socketMessageListener;
150 this.conn.onclose = this.socketCloseListener;
151 // Socket init required before loading remote game:
152 const socketInit = callback => {
153 if (!!this.conn && this.conn.readyState == 1)
157 // Socket not ready yet (initial loading)
158 // NOTE: it's important to call callback without arguments,
159 // otherwise first arg is Websocket object and loadGame fails.
160 this.conn.onopen = () => callback();
162 if (!this.gameRef.rid)
163 // Game stored locally or on server
164 this.loadGame(null, () => socketInit(this.roomInit));
166 // Game stored remotely: need socket to retrieve it
167 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
168 // --> It will be given when receiving "fullgame" socket event.
169 socketInit(this.loadGame);
171 mounted: function() {
173 .getElementById("chatWrap")
174 .addEventListener("click", processModalClick);
176 beforeDestroy: function() {
177 this.send("disconnect");
180 roomInit: function() {
181 if (!this.roomInitialized) {
182 // Notify the room only now that I connected, because
183 // messages might be lost otherwise (if game loading is slow)
184 this.send("connect");
185 this.send("pollclients");
186 // We may ask fullgame several times if some moves are lost,
187 // but room should be init only once:
188 this.roomInitialized = true;
191 send: function(code, obj) {
193 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
195 isConnected: function(index) {
196 const player = this.game.players[index];
198 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
200 // Try to find a match in people:
204 Object.keys(this.people).some(sid => sid == player.sid)
209 Object.values(this.people).some(p => p.id == player.uid)
213 resetChatColor: function() {
214 // TODO: this is called twice, once on opening an once on closing
215 document.getElementById("chatBtn").classList.remove("somethingnew");
217 processChat: function(chat) {
218 this.send("newchat", { data: chat });
219 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
220 if (this.game.type == "corr" && this.st.user.id > 0)
221 GameStorage.update(this.gameRef.id, { chat: chat });
223 clearChat: function() {
224 // Nothing more to do if game is live (chats not recorded)
225 if (this.game.type == "corr") {
226 if (!!this.game.mycolor)
227 ajax("/chats", "DELETE", {gid: this.game.id});
228 this.game.chats = [];
231 // Notify turn after a new move (to opponent and me on MyGames page)
232 notifyTurn: function(sid) {
233 const player = this.people[sid];
234 const colorIdx = this.game.players.findIndex(
235 p => p.sid == sid || p.id == player.id);
236 const color = ["w","b"][colorIdx];
240 this.game.movesCount % 2 == 0
245 this.game.movesCount % 2 == 1
247 this.send("turnchange", { target: sid, yourTurn: yourTurn });
249 socketMessageListener: function(msg) {
250 if (!this.conn) return;
251 const data = JSON.parse(msg.data);
254 data.sockIds.forEach(sid => {
255 if (sid != this.st.user.sid) {
256 this.send("askidentity", { target: sid });
257 // Ask potentially missed last state, if opponent and I play
259 !!this.game.mycolor &&
260 this.game.type == "live" &&
261 this.game.score == "*" &&
262 this.game.players.some(p => p.sid == sid)
264 this.send("asklastate", { target: sid });
270 if (!this.people[data.from]) {
271 this.newConnect[data.from] = true; //for self multi-connects tests
272 this.send("askidentity", { target: data.from });
276 this.$delete(this.people, data.from);
279 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
280 // Either me (another tab) or opponent
281 const sid = data.from;
282 if (!this.onMygames.some(s => s == sid))
284 this.onMygames.push(sid);
285 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
288 if (!this.people[sid])
289 this.send("askidentity", { target: sid });
292 ArrayFun.remove(this.onMygames, sid => sid == data.from);
295 // I logged in elsewhere:
297 alert(this.st.tr["New connexion detected: tab now offline"]);
299 case "askidentity": {
300 // Request for identification
302 // Decompose to avoid revealing email
303 name: this.st.user.name,
304 sid: this.st.user.sid,
307 this.send("identity", { data: me, target: data.from });
311 const user = data.data;
312 this.$set(this.people, user.sid, { name: user.name, id: user.id });
313 // If I multi-connect, kill current connexion if no mark (I'm older)
314 if (this.newConnect[user.sid]) {
317 user.id == this.st.user.id &&
318 user.sid != this.st.user.sid &&
319 !this.killed[this.st.user.sid]
321 this.send("killme", { sid: this.st.user.sid });
322 this.killed[this.st.user.sid] = true;
324 delete this.newConnect[user.sid];
329 // Send current (live) game if not asked by any of the players
331 this.game.type == "live" &&
332 this.game.players.every(p => p.sid != data.from[0])
337 players: this.game.players,
339 cadence: this.game.cadence,
340 score: this.game.score,
341 rid: this.st.user.sid //useful in Hall if I'm an observer
343 this.send("game", { data: myGame, target: data.from });
347 this.send("fullgame", { data: this.game, target: data.from });
350 // Callback "roomInit" to poll clients only after game is loaded
351 let game = data.data;
352 // Move format isn't the same in storage and in browser,
353 // because of the 'addTime' field.
354 game.moves = game.moves.map(m => { return m.move || m; });
355 this.loadGame(game, this.roomInit);
358 // Sending last state if I played a move or score != "*"
360 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
361 this.game.score != "*" ||
362 this.drawOffer == "sent"
364 // Send our "last state" informations to opponent
365 const L = this.game.moves.length;
366 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
368 // NOTE: lastMove (when defined) includes addTime
369 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
370 // Since we played a move (or abort or resign),
371 // only drawOffer=="sent" is possible
372 drawSent: this.drawOffer == "sent",
373 score: this.game.score,
375 initime: this.game.initime[1 - myIdx] //relevant only if I played
377 this.send("lastate", { data: myLastate, target: data.from });
380 case "lastate": //got opponent infos about last move
381 this.lastate = data.data;
382 if (this.game.rendered)
383 // Game is rendered (Board component)
384 this.processLastate();
385 // Else: will be processed when game is ready
388 const move = data.data;
389 if (move.index > this.game.movesCount && !this.fullGameRequested) {
390 // This can only happen if I'm an observer and missed a move:
391 // just ask fullgame again, this is much simpler.
392 (function askIfPeerConnected() {
393 if (!!this.people[this.gameRef.rid])
394 this.send("askfullgame", { target: this.gameRef.rid });
395 else setTimeout(askIfPeerConnected, 1000);
397 this.fullGameRequested = true;
400 move.index < this.game.movesCount ||
401 this.gotMoveIdx >= move.index
403 // Opponent re-send but we already have the move:
404 // (maybe he didn't receive our pingback...)
405 // TODO: currently, all opponent game tabs will receive this
406 this.send("gotmove", {index: move.index, target: data.from});
408 const receiveMyMove = (
409 !!this.game.mycolor &&
410 move.index == this.game.movesCount
412 if (!receiveMyMove && !!this.game.mycolor)
413 // Notify opponent that I got the move:
414 this.send("gotmove", {index: move.index, target: data.from});
415 if (move.cancelDrawOffer) {
416 // Opponent refuses draw
418 // NOTE for corr games: drawOffer reset by player in turn
420 this.game.type == "live" &&
421 !!this.game.mycolor &&
424 GameStorage.update(this.gameRef.id, { drawOffer: "" });
427 this.$refs["basegame"].play(
432 addTime: move.addTime,
433 receiveMyMove: receiveMyMove
441 this.opponentGotMove = true;
444 /// TODO: same strategy for askLastate
445 // --> the message could not have been received,
446 // or maybe we ddn't receive it back.
450 const score = data.side == "b" ? "1-0" : "0-1";
451 const side = data.side == "w" ? "White" : "Black";
452 this.gameOver(score, side + " surrender");
455 this.gameOver("?", "Stop");
458 this.gameOver("1/2", data.data);
461 // NOTE: observers don't know who offered draw
462 this.drawOffer = "received";
465 this.newChat = data.data;
466 if (!document.getElementById("modalChat").checked)
467 document.getElementById("chatBtn").classList.add("somethingnew");
471 socketCloseListener: function() {
472 this.conn = new WebSocket(this.connexionString);
473 this.conn.addEventListener("message", this.socketMessageListener);
474 this.conn.addEventListener("close", this.socketCloseListener);
476 // lastate was received, but maybe game wasn't ready yet:
477 processLastate: function() {
478 const data = this.lastate;
479 this.lastate = undefined; //security...
480 const L = this.game.moves.length;
481 if (data.movesCount > L) {
482 // Just got last move from him
483 this.$refs["basegame"].play(
487 {addTime: data.lastMove.addTime, initime: data.initime});
489 if (data.drawSent) this.drawOffer = "received";
490 if (data.score != "*") {
492 if (this.game.score == "*") this.gameOver(data.score);
495 clickDraw: function() {
496 if (!this.game.mycolor) return; //I'm just spectator
497 if (["received", "threerep"].includes(this.drawOffer)) {
498 if (!confirm(this.st.tr["Accept draw?"])) return;
500 this.drawOffer == "received"
502 : "Three repetitions";
503 this.send("draw", { data: message });
504 this.gameOver("1/2", message);
505 } else if (this.drawOffer == "") {
506 // No effect if drawOffer == "sent"
507 if (!!this.game.mycolor != this.vr.turn) {
508 alert(this.st.tr["Draw offer only in your turn"]);
511 if (!confirm(this.st.tr["Offer draw?"])) return;
512 this.drawOffer = "sent";
513 this.send("drawoffer");
514 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
517 abortGame: function() {
518 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
519 this.gameOver("?", "Stop");
523 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
525 this.send("resign", { data: this.game.mycolor });
526 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
527 const side = this.game.mycolor == "w" ? "White" : "Black";
528 this.gameOver(score, side + " surrender");
530 // 3 cases for loading a game:
531 // - from indexedDB (running or completed live game I play)
532 // - from server (one correspondance game I play[ed] or not)
533 // - from remote peer (one live game I don't play, finished or not)
534 loadGame: function(game, callback) {
535 const afterRetrieval = async game => {
536 const vModule = await import("@/variants/" + game.vname + ".js");
537 window.V = vModule.VariantRules;
538 this.vr = new V(game.fen);
539 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
540 const tc = extractTime(game.cadence);
541 const myIdx = game.players.findIndex(p => {
542 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
544 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
545 if (!game.chats) game.chats = []; //live games don't have chat history
546 if (gtype == "corr") {
547 if (game.players[0].color == "b") {
548 // Adopt the same convention for live and corr games: [0] = white
549 [game.players[0], game.players[1]] = [
554 // NOTE: clocks in seconds, initime in milliseconds
555 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
556 const L = game.moves.length;
557 if (game.score == "*") {
558 // Set clocks + initime
559 game.clocks = [tc.mainTime, tc.mainTime];
560 game.initime = [0, 0];
562 const gameLastupdate = game.moves[L-1].played;
563 game.initime[L % 2] = gameLastupdate;
566 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
570 // Sort chat messages from newest to oldest
571 game.chats.sort((c1, c2) => {
572 return c2.added - c1.added;
574 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
575 // Did a chat message arrive after my last move?
577 if (L == 1 && myIdx == 0)
578 dtLastMove = game.moves[0].played;
581 // It's now white turn
582 dtLastMove = game.moves[L-1-(1-myIdx)].played;
585 dtLastMove = game.moves[L-1-myIdx].played;
588 if (dtLastMove < game.chats[0].added)
589 document.getElementById("chatBtn").classList.add("somethingnew");
591 // Now that we used idx and played, re-format moves as for live games
592 game.moves = game.moves.map(m => m.squares);
594 if (gtype == "live" && game.clocks[0] < 0) {
596 game.clocks = [tc.mainTime, tc.mainTime];
597 if (game.score == "*") {
598 game.initime[0] = Date.now();
600 // I play in this live game; corr games don't have clocks+initime
601 GameStorage.update(game.id, {
603 initime: game.initime
608 if (game.drawOffer) {
609 if (game.drawOffer == "t")
611 this.drawOffer = "threerep";
613 // Draw offered by any of the players:
614 if (myIdx < 0) this.drawOffer = "received";
616 // I play in this game:
618 (game.drawOffer == "w" && myIdx == 0) ||
619 (game.drawOffer == "b" && myIdx == 1)
621 this.drawOffer = "sent";
622 else this.drawOffer = "received";
626 this.repeat = {}; //reset: scan past moves' FEN:
628 let vr_tmp = new V(game.fenStart);
630 game.moves.forEach(m => {
632 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
633 this.repeat[fenIdx] = this.repeat[fenIdx]
634 ? this.repeat[fenIdx] + 1
637 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
638 this.game = Object.assign(
639 // NOTE: assign mycolor here, since BaseGame could also be VS computer
642 increment: tc.increment,
644 // opponent sid not strictly required (or available), but easier
645 // at least oppsid or oppid is available anyway:
646 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
647 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
648 movesCount: game.moves.length
652 if (this.fullGameRequested)
653 // Second (or more) time the full game is asked:
654 this.fullGameRequested = false;
656 this.$nextTick(() => {
657 this.game.rendered = true;
658 // Did lastate arrive before game was rendered?
659 if (this.lastate) this.processLastate();
661 if (callback) callback();
664 afterRetrieval(game);
667 if (this.gameRef.rid) {
668 // Remote live game: forgetting about callback func... (TODO: design)
669 this.send("askfullgame", { target: this.gameRef.rid });
671 // Local or corr game
672 // NOTE: afterRetrieval() is never called if game not found
673 GameStorage.get(this.gameRef.id, afterRetrieval);
676 re_setClocks: function() {
677 if (this.game.movesCount < 2 || this.game.score != "*") {
678 // 1st move not completed yet, or game over: freeze time
679 this.virtualClocks = this.game.clocks.map(s => ppt(s));
682 const currentTurn = this.vr.turn;
683 const currentMovesCount = this.game.moves.length;
684 const colorIdx = ["w", "b"].indexOf(currentTurn);
686 this.game.clocks[colorIdx] -
687 (Date.now() - this.game.initime[colorIdx]) / 1000;
688 this.virtualClocks = [0, 1].map(i => {
690 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
691 return ppt(this.game.clocks[i] - removeTime);
693 let clockUpdate = setInterval(() => {
696 this.game.moves.length > currentMovesCount ||
697 this.game.score != "*"
699 clearInterval(clockUpdate);
702 currentTurn == "w" ? "0-1" : "1-0",
709 ppt(Math.max(0, --countdown))
713 // Post-process a (potentially partial) move (which was just played in BaseGame)
714 processMove: function(move, data) {
715 const moveCol = this.vr.turn;
716 const doProcessMove = () => {
717 const colorIdx = ["w", "b"].indexOf(moveCol);
718 const nextIdx = 1 - colorIdx;
719 if (!!this.game.mycolor && !data.receiveMyMove) {
720 // NOTE: 'var' to see that variable outside this block
721 var filtered_move = getFilteredMove(move);
723 // Send move ("newmove" event) to people in the room (if our turn)
724 let addTime = (data && this.game.type == "live") ? data.addTime : 0;
725 if (moveCol == this.game.mycolor && !data.receiveMyMove) {
726 if (this.drawOffer == "received")
729 // 'addTime' is irrelevant for corr games:
730 if (this.game.type == "live" && this.game.movesCount >= 2) {
731 const elapsed = Date.now() - this.game.initime[colorIdx];
732 // elapsed time is measured in milliseconds
733 addTime = this.game.increment - elapsed / 1000;
737 index: this.game.movesCount,
738 addTime: addTime, //undefined for corr games
739 cancelDrawOffer: this.drawOffer == ""
741 this.opponentGotMove = false;
742 this.send("newmove", { data: sendMove });
744 // TODO: setInterval 500ms to 1s (750?) : if !gotMove (with the right index), re-send
747 // Update current game object (no need for moves stack):
748 playMove(move, this.vr);
749 this.game.movesCount++;
750 // TODO: notifyTurn: "changeturn" message
751 // (add)Time indication: useful in case of lastate infos requested
752 this.game.moves.push(this.game.type == "live"
753 ? {move:move, addTime:addTime}
755 this.game.fen = this.vr.getFen();
756 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
757 // In corr games, just reset clock to mainTime:
758 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
759 // data.initime is set only when I receive a "lastate" move from opponent
760 this.game.initime[nextIdx] = (data && data.initime) ? data.initime : Date.now();
762 // If repetition detected, consider that a draw offer was received:
763 const fenObj = this.vr.getFenForRepeat();
764 this.repeat[fenObj] = this.repeat[fenObj] ? this.repeat[fenObj] + 1 : 1;
765 if (this.repeat[fenObj] >= 3) this.drawOffer = "threerep";
766 else if (this.drawOffer == "threerep") this.drawOffer = "";
767 // Since corr games are stored at only one location, update should be
768 // done only by one player for each move:
770 !!this.game.mycolor &&
771 !data.receiveMyMove &&
772 (this.game.type == "live" || moveCol == this.game.mycolor)
775 switch (this.drawOffer) {
780 drawCode = this.game.mycolor;
783 drawCode = V.GetOppCol(this.game.mycolor);
786 if (this.game.type == "corr") {
787 GameStorage.update(this.gameRef.id, {
790 squares: filtered_move,
792 idx: this.game.moves.length - 1
794 // Code "n" for "None" to force reset (otherwise it's ignored)
795 drawOffer: drawCode || "n"
800 GameStorage.update(this.gameRef.id, {
803 clocks: this.game.clocks,
804 initime: this.game.initime,
811 this.game.type == "corr" &&
812 moveCol == this.game.mycolor &&
816 // TODO: remplacer cette confirm box par qqch de plus discret
817 // (et de même pour challenge accepté / refusé)
820 this.st.tr["Move played:"] +
822 getFullNotation(move) +
824 this.st.tr["Are you sure?"]
827 this.$refs["basegame"].cancelLastMove();
831 // Let small time to finish drawing current move attempt:
834 else doProcessMove();
836 gameOver: function(score, scoreMsg) {
837 this.game.score = score;
838 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
839 const myIdx = this.game.players.findIndex(p => {
840 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
843 // OK, I play in this game
844 GameStorage.update(this.gameRef.id, {
848 // Notify the score to main Hall. TODO: only one player (currently double send)
849 this.send("result", { gid: this.game.id, score: score });
856 <style lang="sass" scoped>
858 background-color: lightgreen
870 @media screen and (min-width: 768px)
873 @media screen and (max-width: 767px)
878 display: inline-block
881 display: inline-block
884 @media screen and (max-width: 767px)
887 @media screen and (min-width: 768px)
904 display: inline-block
908 display: inline-block
919 .draw-sent, .draw-sent:hover
920 background-color: lightyellow
922 .draw-received, .draw-received:hover
923 background-color: lightgreen
925 .draw-threerep, .draw-threerep:hover
926 background-color: #e4d1fc
929 background-color: #c5fefe