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)")
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
113 // Related to (killing of) self multi-connects:
119 $route: function(to) {
120 this.gameRef.id = to.params["id"];
121 this.gameRef.rid = to.query["rid"];
125 // NOTE: some redundant code with Hall.vue (mostly related to people array)
126 created: function() {
127 // Always add myself to players' list
128 const my = this.st.user;
129 this.$set(this.people, my.sid, { id: my.id, name: my.name });
130 this.gameRef.id = this.$route.params["id"];
131 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
132 // Initialize connection
133 this.connexionString =
140 encodeURIComponent(this.$route.path);
141 this.conn = new WebSocket(this.connexionString);
142 this.conn.onmessage = this.socketMessageListener;
143 this.conn.onclose = this.socketCloseListener;
144 // Socket init required before loading remote game:
145 const socketInit = callback => {
146 if (!!this.conn && this.conn.readyState == 1)
150 // Socket not ready yet (initial loading)
151 // NOTE: it's important to call callback without arguments,
152 // otherwise first arg is Websocket object and loadGame fails.
153 this.conn.onopen = () => callback();
155 if (!this.gameRef.rid)
156 // Game stored locally or on server
157 this.loadGame(null, () => socketInit(this.roomInit));
159 // Game stored remotely: need socket to retrieve it
160 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
161 // --> It will be given when receiving "fullgame" socket event.
162 socketInit(this.loadGame);
164 mounted: function() {
166 .getElementById("chatWrap")
167 .addEventListener("click", processModalClick);
169 beforeDestroy: function() {
170 this.send("disconnect");
173 roomInit: function() {
174 // Notify the room only now that I connected, because
175 // messages might be lost otherwise (if game loading is slow)
176 this.send("connect");
177 this.send("pollclients");
179 send: function(code, obj) {
181 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
183 isConnected: function(index) {
184 const player = this.game.players[index];
186 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
188 // Try to find a match in people:
192 Object.keys(this.people).some(sid => sid == player.sid)
197 Object.values(this.people).some(p => p.id == player.uid)
201 resetChatColor: function() {
202 // TODO: this is called twice, once on opening an once on closing
203 document.getElementById("chatBtn").classList.remove("somethingnew");
205 processChat: function(chat) {
206 this.send("newchat", { data: chat });
207 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
208 if (this.game.type == "corr" && this.st.user.id > 0)
209 GameStorage.update(this.gameRef.id, { chat: chat });
211 clearChat: function() {
212 // Nothing more to do if game is live (chats not recorded)
213 if (this.game.type == "corr") {
214 if (this.game.mycolor)
215 ajax("/chats", "DELETE", {gid: this.game.id});
216 this.game.chats = [];
219 // Notify turn after a new move (to opponent and me on MyGames page)
220 notifyTurn: function(sid) {
221 const player = this.people[sid];
222 const colorIdx = this.game.players.findIndex(
223 p => p.sid == sid || p.id == player.id);
224 const color = ["w","b"][colorIdx];
228 this.game.movesCount % 2 == 0
233 this.game.movesCount % 2 == 1
235 this.send("turnchange", { target: sid, yourTurn: yourTurn });
237 socketMessageListener: function(msg) {
238 if (!this.conn) return;
239 const data = JSON.parse(msg.data);
242 data.sockIds.forEach(sid => {
243 this.$set(this.people, sid, { id: 0, name: "" });
244 if (sid != this.st.user.sid) {
245 this.send("askidentity", { target: sid });
246 // Ask potentially missed last state, if opponent and I play
248 !!this.game.mycolor &&
249 this.game.type == "live" &&
250 this.game.score == "*" &&
251 this.game.players.some(p => p.sid == sid)
253 this.send("asklastate", { target: sid });
259 if (!this.people[data.from])
260 // TODO: people array should be init only after identity is known
261 this.$set(this.people, data.from, { name: "", id: 0 });
262 if (!this.people[data.from].name) {
263 this.newConnect[data.from] = true; //for self multi-connects tests
264 this.send("askidentity", { target: data.from });
268 this.$delete(this.people, data.from);
272 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
273 // Either me (another tab) or opponent
274 const sid = data.from;
275 if (!this.onMygames.some(s => s == sid))
277 this.onMygames.push(sid);
278 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
281 if (!this.people[sid])
282 this.send("askidentity", { target: sid });
285 ArrayFun.remove(this.onMygames, sid => sid == data.from);
288 // I logged in elsewhere:
290 alert(this.st.tr["New connexion detected: tab now offline"]);
292 case "askidentity": {
293 // Request for identification (TODO: anonymous shouldn't need to reply)
295 // Decompose to avoid revealing email
296 name: this.st.user.name,
297 sid: this.st.user.sid,
300 this.send("identity", { data: me, target: data.from });
304 // TODO: init people array here.
305 const user = data.data;
307 // If I multi-connect, kill current connexion if no mark (I'm older)
309 this.newConnect[user.sid] &&
311 user.id == this.st.user.id &&
312 user.sid != this.st.user.sid
314 if (!this.killed[this.st.user.sid]) {
315 this.send("killme", { sid: this.st.user.sid });
316 this.killed[this.st.user.sid] = true;
319 if (user.sid != this.st.user.sid) {
320 //I already know my identity...
321 this.$set(this.people, user.sid, {
327 delete this.newConnect[user.sid];
331 // Send current (live) game if not asked by any of the players
333 this.game.type == "live" &&
334 this.game.players.every(p => p.sid != data.from[0])
339 players: this.game.players,
341 cadence: this.game.cadence,
342 score: this.game.score,
343 rid: this.st.user.sid //useful in Hall if I'm an observer
345 this.send("game", { data: myGame, target: data.from });
349 this.send("fullgame", { data: this.game, target: data.from });
352 // Callback "roomInit" to poll clients only after game is loaded
353 let game = data.data;
354 // Move format isn't the same in storage and in browser,
355 // because of the 'addTime' field.
356 game.moves = game.moves.map(m => { return m.move || m; });
357 this.loadGame(game, this.roomInit);
360 // Sending last state if I played a move or score != "*"
362 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
363 this.game.score != "*" ||
364 this.drawOffer == "sent"
366 // Send our "last state" informations to opponent
367 const L = this.game.moves.length;
368 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
370 // NOTE: lastMove (when defined) includes addTime
371 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
372 // Since we played a move (or abort or resign),
373 // only drawOffer=="sent" is possible
374 drawSent: this.drawOffer == "sent",
375 score: this.game.score,
377 initime: this.game.initime[1 - myIdx] //relevant only if I played
379 this.send("lastate", { data: myLastate, target: data.from });
382 case "lastate": //got opponent infos about last move
383 this.lastate = data.data;
384 if (this.game.rendered)
385 // Game is rendered (Board component)
386 this.processLastate();
387 // Else: will be processed when game is ready
390 const move = data.data;
391 if (move.cancelDrawOffer) {
392 // Opponent refuses draw
394 // NOTE for corr games: drawOffer reset by player in turn
395 if (this.game.type == "live" && !!this.game.mycolor)
396 GameStorage.update(this.gameRef.id, { drawOffer: "" });
398 this.$refs["basegame"].play(
402 {addTime: move.addTime});
406 const score = data.side == "b" ? "1-0" : "0-1";
407 const side = data.side == "w" ? "White" : "Black";
408 this.gameOver(score, side + " surrender");
411 this.gameOver("?", "Stop");
414 this.gameOver("1/2", data.data);
417 // NOTE: observers don't know who offered draw
418 this.drawOffer = "received";
421 this.newChat = data.data;
422 if (!document.getElementById("modalChat").checked)
423 document.getElementById("chatBtn").classList.add("somethingnew");
427 socketCloseListener: function() {
428 this.conn = new WebSocket(this.connexionString);
429 this.conn.addEventListener("message", this.socketMessageListener);
430 this.conn.addEventListener("close", this.socketCloseListener);
432 // lastate was received, but maybe game wasn't ready yet:
433 processLastate: function() {
434 const data = this.lastate;
435 this.lastate = undefined; //security...
436 const L = this.game.moves.length;
437 if (data.movesCount > L) {
438 // Just got last move from him
439 this.$refs["basegame"].play(
443 {addTime: data.lastMove.addTime, initime: data.initime});
445 if (data.drawSent) this.drawOffer = "received";
446 if (data.score != "*") {
448 if (this.game.score == "*") this.gameOver(data.score);
451 clickDraw: function() {
452 if (!this.game.mycolor) return; //I'm just spectator
453 if (["received", "threerep"].includes(this.drawOffer)) {
454 if (!confirm(this.st.tr["Accept draw?"])) return;
456 this.drawOffer == "received"
458 : "Three repetitions";
459 this.send("draw", { data: message });
460 this.gameOver("1/2", message);
461 } else if (this.drawOffer == "") {
462 // No effect if drawOffer == "sent"
463 if (this.game.mycolor != this.vr.turn) {
464 alert(this.st.tr["Draw offer only in your turn"]);
467 if (!confirm(this.st.tr["Offer draw?"])) return;
468 this.drawOffer = "sent";
469 this.send("drawoffer");
470 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
473 abortGame: function() {
474 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
475 this.gameOver("?", "Stop");
479 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
481 this.send("resign", { data: this.game.mycolor });
482 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
483 const side = this.game.mycolor == "w" ? "White" : "Black";
484 this.gameOver(score, side + " surrender");
486 // 3 cases for loading a game:
487 // - from indexedDB (running or completed live game I play)
488 // - from server (one correspondance game I play[ed] or not)
489 // - from remote peer (one live game I don't play, finished or not)
490 loadGame: function(game, callback) {
491 const afterRetrieval = async game => {
492 const vModule = await import("@/variants/" + game.vname + ".js");
493 window.V = vModule.VariantRules;
494 this.vr = new V(game.fen);
495 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
496 const tc = extractTime(game.cadence);
497 const myIdx = game.players.findIndex(p => {
498 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
500 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
501 if (!game.chats) game.chats = []; //live games don't have chat history
502 if (gtype == "corr") {
503 if (game.players[0].color == "b") {
504 // Adopt the same convention for live and corr games: [0] = white
505 [game.players[0], game.players[1]] = [
510 // NOTE: clocks in seconds, initime in milliseconds
511 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
512 const L = game.moves.length;
513 if (game.score == "*") {
514 // Set clocks + initime
515 game.clocks = [tc.mainTime, tc.mainTime];
516 game.initime = [0, 0];
518 const gameLastupdate = game.moves[L-1].played;
519 game.initime[L % 2] = gameLastupdate;
522 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
526 // Sort chat messages from newest to oldest
527 game.chats.sort((c1, c2) => {
528 return c2.added - c1.added;
530 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
531 // Did a chat message arrive after my last move?
533 if (L == 1 && myIdx == 0)
534 dtLastMove = game.moves[0].played;
537 // It's now white turn
538 dtLastMove = game.moves[L-1-(1-myIdx)].played;
541 dtLastMove = game.moves[L-1-myIdx].played;
544 if (dtLastMove < game.chats[0].added)
545 document.getElementById("chatBtn").classList.add("somethingnew");
547 // Now that we used idx and played, re-format moves as for live games
548 game.moves = game.moves.map(m => m.squares);
550 if (gtype == "live" && game.clocks[0] < 0) {
552 game.clocks = [tc.mainTime, tc.mainTime];
553 if (game.score == "*") {
554 game.initime[0] = Date.now();
556 // I play in this live game; corr games don't have clocks+initime
557 GameStorage.update(game.id, {
559 initime: game.initime
564 if (game.drawOffer) {
565 if (game.drawOffer == "t")
567 this.drawOffer = "threerep";
569 // Draw offered by any of the players:
570 if (myIdx < 0) this.drawOffer = "received";
572 // I play in this game:
574 (game.drawOffer == "w" && myIdx == 0) ||
575 (game.drawOffer == "b" && myIdx == 1)
577 this.drawOffer = "sent";
578 else this.drawOffer = "received";
582 this.repeat = {}; //reset: scan past moves' FEN:
584 let vr_tmp = new V(game.fenStart);
586 game.moves.forEach(m => {
588 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
589 this.repeat[fenIdx] = this.repeat[fenIdx]
590 ? this.repeat[fenIdx] + 1
593 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
594 this.game = Object.assign(
595 // NOTE: assign mycolor here, since BaseGame could also be VS computer
598 increment: tc.increment,
600 // opponent sid not strictly required (or available), but easier
601 // at least oppsid or oppid is available anyway:
602 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
603 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
604 movesCount: game.moves.length
609 this.$nextTick(() => {
610 this.game.rendered = true;
611 // Did lastate arrive before game was rendered?
612 if (this.lastate) this.processLastate();
614 if (callback) callback();
617 afterRetrieval(game);
620 if (this.gameRef.rid) {
621 // Remote live game: forgetting about callback func... (TODO: design)
622 this.send("askfullgame", { target: this.gameRef.rid });
624 // Local or corr game
625 // NOTE: afterRetrieval() is never called if game not found
626 GameStorage.get(this.gameRef.id, afterRetrieval);
629 re_setClocks: function() {
630 if (this.game.movesCount < 2 || this.game.score != "*") {
631 // 1st move not completed yet, or game over: freeze time
632 this.virtualClocks = this.game.clocks.map(s => ppt(s));
635 const currentTurn = this.vr.turn;
636 const currentMovesCount = this.game.moves.length;
637 const colorIdx = ["w", "b"].indexOf(currentTurn);
639 this.game.clocks[colorIdx] -
640 (Date.now() - this.game.initime[colorIdx]) / 1000;
641 this.virtualClocks = [0, 1].map(i => {
643 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
644 return ppt(this.game.clocks[i] - removeTime);
646 let clockUpdate = setInterval(() => {
649 this.game.moves.length > currentMovesCount ||
650 this.game.score != "*"
652 clearInterval(clockUpdate);
655 currentTurn == "w" ? "0-1" : "1-0",
662 ppt(Math.max(0, --countdown))
666 // Post-process a (potentially partial) move (which was just played in BaseGame)
667 // TODO?: wait for AJAX return to finish processing a move,
668 // and for opponent pingback in case of live game : if none received after e.g. 500ms, re-send newmove
669 // ...and provide move index with newmove event for basic check after receiving
670 processMove: function(move, data) {
671 const moveCol = this.vr.turn;
672 const doProcessMove = () => {
673 const colorIdx = ["w", "b"].indexOf(moveCol);
674 const nextIdx = 1 - colorIdx;
675 if (this.game.mycolor) {
676 // NOTE: 'var' to see that variable outside this block
677 var filtered_move = getFilteredMove(move);
679 // Send move ("newmove" event) to people in the room (if our turn)
680 let addTime = (data && this.game.type == "live") ? data.addTime : 0;
681 if (moveCol == this.game.mycolor) {
682 if (this.drawOffer == "received")
685 // 'addTime' is irrelevant for corr games:
686 if (this.game.type == "live" && this.game.movesCount >= 2) {
687 const elapsed = Date.now() - this.game.initime[colorIdx];
688 // elapsed time is measured in milliseconds
689 addTime = this.game.increment - elapsed / 1000;
693 addTime: addTime, //undefined for corr games
694 cancelDrawOffer: this.drawOffer == "",
695 // Players' SID required for /mygames page
696 // TODO: precompute and add this field to game object?
697 players: this.game.players.map(p => p.sid)
699 this.send("newmove", { data: sendMove });
701 // Update current game object (no need for moves stack):
702 playMove(move, this.vr);
703 this.game.movesCount++;
705 // (add)Time indication: useful in case of lastate infos requested
706 this.game.moves.push(this.game.type == "live"
707 ? {move:move, addTime:addTime}
709 this.game.fen = this.vr.getFen();
710 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
711 // In corr games, just reset clock to mainTime:
712 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
713 // data.initime is set only when I receive a "lastate" move from opponent
714 this.game.initime[nextIdx] = (data && data.initime) ? data.initime : Date.now();
716 // If repetition detected, consider that a draw offer was received:
717 const fenObj = V.ParseFen(this.game.fen);
718 let repIdx = fenObj.position + "_" + fenObj.turn;
719 if (fenObj.flags) repIdx += "_" + fenObj.flags;
720 this.repeat[repIdx] = this.repeat[repIdx] ? this.repeat[repIdx] + 1 : 1;
721 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
722 else if (this.drawOffer == "threerep") this.drawOffer = "";
723 // Since corr games are stored at only one location, update should be
724 // done only by one player for each move:
727 (this.game.type == "live" || moveCol == this.game.mycolor)
730 switch (this.drawOffer) {
735 drawCode = this.game.mycolor;
738 drawCode = V.GetOppCol(this.game.mycolor);
741 if (this.game.type == "corr") {
742 GameStorage.update(this.gameRef.id, {
745 squares: filtered_move,
747 idx: this.game.moves.length - 1
749 // Code "n" for "None" to force reset (otherwise it's ignored)
750 drawOffer: drawCode || "n"
755 GameStorage.update(this.gameRef.id, {
758 clocks: this.game.clocks,
759 initime: this.game.initime,
765 if (this.game.type == "corr" && moveCol == this.game.mycolor) {
769 this.st.tr["Move played:"] +
771 getFullNotation(move) +
773 this.st.tr["Are you sure?"]
776 this.$refs["basegame"].cancelLastMove();
780 // Let small time to finish drawing current move attempt:
783 else doProcessMove();
785 gameOver: function(score, scoreMsg) {
786 this.game.score = score;
787 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
788 const myIdx = this.game.players.findIndex(p => {
789 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
792 // OK, I play in this game
793 GameStorage.update(this.gameRef.id, {
797 // Notify the score to main Hall. TODO: only one player (currently double send)
798 this.send("result", { gid: this.game.id, score: score });
805 <style lang="sass" scoped>
807 background-color: lightgreen
819 @media screen and (min-width: 768px)
822 @media screen and (max-width: 767px)
827 display: inline-block
830 display: inline-block
833 @media screen and (max-width: 767px)
836 @media screen and (min-width: 768px)
853 display: inline-block
857 display: inline-block
868 .draw-sent, .draw-sent:hover
869 background-color: lightyellow
871 .draw-received, .draw-received:hover
872 background-color: lightgreen
874 .draw-threerep, .draw-threerep:hover
875 background-color: #e4d1fc
878 background-color: #c5fefe