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"
29 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
30 span.variant-cadence {{ game.cadence }}
31 span.variant-name {{ game.vname }}
32 button#chatBtn(onClick="window.doClick('modalChat')") Chat
33 #actions(v-if="game.score=='*'")
36 :class="{['draw-' + drawOffer]: true}"
43 | {{ st.tr["Abort"] }}
48 | {{ st.tr["Resign"] }}
51 span.name(:class="{connected: isConnected(0)}")
52 | {{ game.players[0].name || "@nonymous" }}
53 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
55 span.name(:class="{connected: isConnected(1)}")
56 | {{ game.players[1].name || "@nonymous" }}
57 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
61 @newmove="processMove"
67 import BaseGame from "@/components/BaseGame.vue";
68 import Chat from "@/components/Chat.vue";
69 import { store } from "@/store";
70 import { GameStorage } from "@/utils/gameStorage";
71 import { ppt } from "@/utils/datetime";
72 import { extractTime } from "@/utils/timeControl";
73 import { getRandString } from "@/utils/alea";
74 import { processModalClick } from "@/utils/modalClick";
75 import { getScoreMessage } from "@/utils/scoring";
76 import params from "@/parameters";
83 // gameRef: to find the game in (potentially remote) storage
88 //given in URL (rid = remote ID)
94 players: [{ name: "" }, { name: "" }],
98 virtualClocks: [0, 0], //initialized with true game.clocks
99 vr: null, //"variant rules" object initialized from FEN
101 people: {}, //players + observers
102 lastate: undefined, //used if opponent send lastate before game is ready
103 repeat: {}, //detect position repetition
107 // Related to (killing of) self multi-connects:
113 $route: function(to) {
114 this.gameRef.id = to.params["id"];
115 this.gameRef.rid = to.query["rid"];
119 // NOTE: some redundant code with Hall.vue (mostly related to people array)
120 created: function() {
121 // Always add myself to players' list
122 const my = this.st.user;
123 this.$set(this.people, my.sid, { id: my.id, name: my.name });
124 this.gameRef.id = this.$route.params["id"];
125 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
126 // Initialize connection
127 this.connexionString =
134 encodeURIComponent(this.$route.path);
135 this.conn = new WebSocket(this.connexionString);
136 this.conn.onmessage = this.socketMessageListener;
137 this.conn.onclose = this.socketCloseListener;
138 // Socket init required before loading remote game:
139 const socketInit = callback => {
140 if (!!this.conn && this.conn.readyState == 1)
143 //socket not ready yet (initial loading)
145 // NOTE: it's important to call callback without arguments,
146 // otherwise first arg is Websocket object and loadGame fails.
147 this.conn.onopen = () => {
152 if (!this.gameRef.rid)
153 //game stored locally or on server
154 this.loadGame(null, () => socketInit(this.roomInit));
155 //game stored remotely: need socket to retrieve it
157 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
158 // --> It will be given when receiving "fullgame" socket event.
159 // A more general approach would be to store it somewhere.
160 socketInit(this.loadGame);
163 mounted: function() {
165 .getElementById("chatWrap")
166 .addEventListener("click", processModalClick);
168 beforeDestroy: function() {
169 this.send("disconnect");
172 roomInit: function() {
173 // Notify the room only now that I connected, because
174 // messages might be lost otherwise (if game loading is slow)
175 this.send("connect");
176 this.send("pollclients");
178 send: function(code, obj) {
180 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:
190 Object.keys(this.people).some(sid => sid == player.sid) ||
191 Object.values(this.people).some(p => p.id == player.uid)
194 socketMessageListener: function(msg) {
195 if (!this.conn) return;
196 const data = JSON.parse(msg.data);
199 data.sockIds.forEach(sid => {
200 this.$set(this.people, sid, { id: 0, name: "" });
201 if (sid != this.st.user.sid) {
202 this.send("askidentity", { target: sid });
203 // Ask potentially missed last state, if opponent and I play
205 !!this.game.mycolor &&
206 this.game.type == "live" &&
207 this.game.score == "*" &&
208 this.game.players.some(p => p.sid == sid)
210 this.send("asklastate", { target: sid });
216 if (!this.people[data.from])
217 this.$set(this.people, data.from, { name: "", id: 0 });
218 if (!this.people[data.from].name) {
219 this.newConnect[data.from] = true; //for self multi-connects tests
220 this.send("askidentity", { target: data.from });
224 this.$delete(this.people, data.from);
227 // I logged in elsewhere:
228 alert(this.st.tr["New connexion detected: tab now offline"]);
229 // TODO: this fails. See https://github.com/websockets/ws/issues/489
230 //this.conn.removeEventListener("message", this.socketMessageListener);
231 //this.conn.removeEventListener("close", this.socketCloseListener);
235 case "askidentity": {
236 // Request for identification (TODO: anonymous shouldn't need to reply)
238 // Decompose to avoid revealing email
239 name: this.st.user.name,
240 sid: this.st.user.sid,
243 this.send("identity", { data: me, target: data.from });
247 const user = data.data;
249 // If I multi-connect, kill current connexion if no mark (I'm older)
251 this.newConnect[user.sid] &&
253 user.id == this.st.user.id &&
254 user.sid != this.st.user.sid
256 if (!this.killed[this.st.user.sid]) {
257 this.send("killme", { sid: this.st.user.sid });
258 this.killed[this.st.user.sid] = true;
261 if (user.sid != this.st.user.sid) {
262 //I already know my identity...
263 this.$set(this.people, user.sid, {
269 delete this.newConnect[user.sid];
273 // Send current (live) game if not asked by any of the players
275 this.game.type == "live" &&
276 this.game.players.every(p => p.sid != data.from[0])
281 players: this.game.players,
283 cadence: this.game.cadence,
284 score: this.game.score,
285 rid: this.st.user.sid //useful in Hall if I'm an observer
287 this.send("game", { data: myGame, target: data.from });
291 this.send("fullgame", { data: this.game, target: data.from });
294 // Callback "roomInit" to poll clients only after game is loaded
295 this.loadGame(data.data, this.roomInit);
298 // Sending last state if I played a move or score != "*"
300 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
301 this.game.score != "*" ||
302 this.drawOffer == "sent"
304 // Send our "last state" informations to opponent
305 const L = this.game.moves.length;
306 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
308 // NOTE: lastMove (when defined) includes addTime
309 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
310 // Since we played a move (or abort or resign),
311 // only drawOffer=="sent" is possible
312 drawSent: this.drawOffer == "sent",
313 score: this.game.score,
315 initime: this.game.initime[1 - myIdx] //relevant only if I played
317 this.send("lastate", { data: myLastate, target: data.from });
320 case "lastate": //got opponent infos about last move
321 this.lastate = data.data;
322 if (this.game.rendered)
323 //game is rendered (Board component)
324 this.processLastate();
325 //else: will be processed when game is ready
328 const move = data.data;
329 if (move.cancelDrawOffer) {
330 //opponent refuses draw
332 // NOTE for corr games: drawOffer reset by player in turn
333 if (this.game.type == "live" && !!this.game.mycolor)
334 GameStorage.update(this.gameRef.id, { drawOffer: "" });
336 this.$set(this.game, "moveToPlay", move);
340 this.gameOver(data.side == "b" ? "1-0" : "0-1", "Resign");
343 this.gameOver("?", "Abort");
346 this.gameOver("1/2", data.data);
349 // NOTE: observers don't know who offered draw
350 this.drawOffer = "received";
353 this.newChat = data.data;
354 if (!document.getElementById("modalChat").checked)
355 document.getElementById("chatBtn").classList.add("somethingnew");
359 socketCloseListener: function() {
360 this.conn = new WebSocket(this.connexionString);
361 this.conn.addEventListener("message", this.socketMessageListener);
362 this.conn.addEventListener("close", this.socketCloseListener);
364 // lastate was received, but maybe game wasn't ready yet:
365 processLastate: function() {
366 const data = this.lastate;
367 this.lastate = undefined; //security...
368 const L = this.game.moves.length;
369 if (data.movesCount > L) {
370 // Just got last move from him
374 Object.assign({ initime: data.initime }, data.lastMove)
377 if (data.drawSent) this.drawOffer = "received";
378 if (data.score != "*") {
380 if (this.game.score == "*") this.gameOver(data.score);
383 clickDraw: function() {
384 if (!this.game.mycolor) return; //I'm just spectator
385 if (["received", "threerep"].includes(this.drawOffer)) {
386 if (!confirm(this.st.tr["Accept draw?"])) return;
388 this.drawOffer == "received"
390 : "Three repetitions";
391 this.send("draw", { data: message });
392 this.gameOver("1/2", message);
393 } else if (this.drawOffer == "") {
394 //no effect if drawOffer == "sent"
395 if (this.game.mycolor != this.vr.turn) {
396 alert(this.st.tr["Draw offer only in your turn"]);
399 if (!confirm(this.st.tr["Offer draw?"])) return;
400 this.drawOffer = "sent";
401 this.send("drawoffer");
402 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
405 abortGame: function() {
406 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
407 this.gameOver("?", "Abort");
411 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
413 this.send("resign", { data: this.game.mycolor });
414 this.gameOver(this.game.mycolor == "w" ? "0-1" : "1-0", "Resign");
416 // 3 cases for loading a game:
417 // - from indexedDB (running or completed live game I play)
418 // - from server (one correspondance game I play[ed] or not)
419 // - from remote peer (one live game I don't play, finished or not)
420 loadGame: function(game, callback) {
421 const afterRetrieval = async game => {
422 const vModule = await import("@/variants/" + game.vname + ".js");
423 window.V = vModule.VariantRules;
424 this.vr = new V(game.fen);
425 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
426 const tc = extractTime(game.cadence);
427 const myIdx = game.players.findIndex(p => {
428 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
430 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
431 if (!game.chats) game.chats = []; //live games don't have chat history
432 if (gtype == "corr") {
433 if (game.players[0].color == "b") {
434 // Adopt the same convention for live and corr games: [0] = white
435 [game.players[0], game.players[1]] = [
440 // corr game: needs to compute the clocks + initime
441 // NOTE: clocks in seconds, initime in milliseconds
442 game.clocks = [tc.mainTime, tc.mainTime];
443 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
444 if (game.score == "*") {
445 //otherwise no need to bother with time
446 game.initime = [0, 0];
447 const L = game.moves.length;
449 let addTime = [0, 0];
450 for (let i = 2; i < L; i++) {
453 (game.moves[i].played - game.moves[i - 1].played) / 1000;
455 for (let i = 0; i <= 1; i++) game.clocks[i] += addTime[i];
457 if (L >= 1) game.initime[L % 2] = game.moves[L - 1].played;
459 const reformattedMoves = game.moves.map(m => {
468 // Sort chat messages from newest to oldest
469 game.chats.sort((c1, c2) => {
470 return c2.added - c1.added;
472 if (myIdx >= 0 && game.chats.length > 0) {
473 // TODO: group multi-moves into an array, to deduce color from index
474 // and not need this (also repeated in BaseGame::re_setVariables())
475 let vr_tmp = new V(game.fenStart); //vr is already at end of game
476 for (let i = 0; i < reformattedMoves.length; i++) {
477 game.moves[i].color = vr_tmp.turn;
478 vr_tmp.play(reformattedMoves[i]);
480 // Blue background on chat button if last chat message arrived after my last move.
482 for (let midx = game.moves.length - 1; midx >= 0; midx--) {
483 if (game.moves[midx].color == mycolor) {
484 dtLastMove = game.moves[midx].played;
488 if (dtLastMove < game.chats[0].added)
489 document.getElementById("chatBtn").classList.add("somethingnew");
491 // Now that we used idx and played, re-format moves as for live games
492 game.moves = reformattedMoves;
494 if (gtype == "live" && game.clocks[0] < 0) {
496 game.clocks = [tc.mainTime, tc.mainTime];
497 if (game.score == "*") {
498 game.initime[0] = Date.now();
500 // I play in this live game; corr games don't have clocks+initime
501 GameStorage.update(game.id, {
503 initime: game.initime
508 if (game.drawOffer) {
509 if (game.drawOffer == "t")
511 this.drawOffer = "threerep";
513 if (myIdx < 0) this.drawOffer = "received";
514 //by any of the players
516 // I play in this game:
518 (game.drawOffer == "w" && myIdx == 0) ||
519 (game.drawOffer == "b" && myIdx == 1)
521 this.drawOffer = "sent";
523 else this.drawOffer = "received";
527 if (game.scoreMsg) game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
528 delete game["moveToPlay"]; //in case of!
529 this.game = Object.assign(
532 // NOTE: assign mycolor here, since BaseGame could also be VS computer
535 increment: tc.increment,
537 // opponent sid not strictly required (or available), but easier
538 // at least oppsid or oppid is available anyway:
539 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
540 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid
544 this.$nextTick(() => {
545 this.game.rendered = true;
546 // Did lastate arrive before game was rendered?
547 if (this.lastate) this.processLastate();
549 this.repeat = {}; //reset: scan past moves' FEN:
551 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
552 let vr_tmp = new V(game.fenStart);
553 game.moves.forEach(m => {
555 const fenObj = V.ParseFen(vr_tmp.getFen());
556 repIdx = fenObj.position + "_" + fenObj.turn;
557 if (fenObj.flags) repIdx += "_" + fenObj.flags;
558 this.repeat[repIdx] = this.repeat[repIdx]
559 ? this.repeat[repIdx] + 1
562 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
563 if (callback) callback();
566 afterRetrieval(game);
569 if (this.gameRef.rid) {
570 // Remote live game: forgetting about callback func... (TODO: design)
571 this.send("askfullgame", { target: this.gameRef.rid });
573 // Local or corr game
574 GameStorage.get(this.gameRef.id, afterRetrieval);
577 re_setClocks: function() {
578 if (this.game.moves.length < 2 || this.game.score != "*") {
579 // 1st move not completed yet, or game over: freeze time
580 this.virtualClocks = this.game.clocks.map(s => ppt(s));
583 const currentTurn = this.vr.turn;
584 const colorIdx = ["w", "b"].indexOf(currentTurn);
586 this.game.clocks[colorIdx] -
587 (Date.now() - this.game.initime[colorIdx]) / 1000;
588 this.virtualClocks = [0, 1].map(i => {
590 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
591 return ppt(this.game.clocks[i] - removeTime);
593 let clockUpdate = setInterval(() => {
596 this.vr.turn != currentTurn ||
597 this.game.score != "*"
599 clearInterval(clockUpdate);
602 this.vr.turn == "w" ? "0-1" : "1-0",
609 ppt(Math.max(0, --countdown))
613 // Post-process a move (which was just played in BaseGame)
614 processMove: function(move) {
615 if (this.game.type == "corr" && move.color == this.game.mycolor) {
618 this.st.tr["Move played:"] +
622 this.st.tr["Are you sure?"]
625 this.$set(this.game, "moveToUndo", move);
629 const colorIdx = ["w", "b"].indexOf(move.color);
630 const nextIdx = ["w", "b"].indexOf(this.vr.turn);
631 // https://stackoverflow.com/a/38750895
632 if (this.game.mycolor) {
633 const allowed_fields = ["appear", "vanish", "start", "end"];
634 // NOTE: 'var' to see this variable outside this block
635 var filtered_move = Object.keys(move)
636 .filter(key => allowed_fields.includes(key))
637 .reduce((obj, key) => {
638 obj[key] = move[key];
642 // Send move ("newmove" event) to people in the room (if our turn)
644 if (move.color == this.game.mycolor) {
645 if (this.drawOffer == "received")
648 if (this.game.moves.length >= 2) {
650 const elapsed = Date.now() - this.game.initime[colorIdx];
651 // elapsed time is measured in milliseconds
652 addTime = this.game.increment - elapsed / 1000;
654 const sendMove = Object.assign({}, filtered_move, {
656 cancelDrawOffer: this.drawOffer == ""
658 this.send("newmove", { data: sendMove });
659 // (Add)Time indication: useful in case of lastate infos requested
660 move.addTime = addTime;
661 } else addTime = move.addTime; //supposed transmitted
662 // Update current game object:
663 this.game.moves.push(move);
664 this.game.fen = move.fen;
665 this.game.clocks[colorIdx] += addTime;
666 // move.initime is set only when I receive a "lastate" move from opponent
667 this.game.initime[nextIdx] = move.initime || Date.now();
669 // If repetition detected, consider that a draw offer was received:
670 const fenObj = V.ParseFen(move.fen);
671 let repIdx = fenObj.position + "_" + fenObj.turn;
672 if (fenObj.flags) repIdx += "_" + fenObj.flags;
673 this.repeat[repIdx] = this.repeat[repIdx] ? this.repeat[repIdx] + 1 : 1;
674 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
675 else if (this.drawOffer == "threerep") this.drawOffer = "";
676 // Since corr games are stored at only one location, update should be
677 // done only by one player for each move:
679 !!this.game.mycolor &&
680 (this.game.type == "live" || move.color == this.game.mycolor)
683 switch (this.drawOffer) {
688 drawCode = this.game.mycolor;
691 drawCode = this.vr.turn;
694 if (this.game.type == "corr") {
695 GameStorage.update(this.gameRef.id, {
698 squares: filtered_move,
700 idx: this.game.moves.length - 1
702 drawOffer: drawCode || "n" //"n" for "None" to force reset (otherwise it's ignored)
706 GameStorage.update(this.gameRef.id, {
709 clocks: this.game.clocks,
710 initime: this.game.initime,
716 resetChatColor: function() {
717 // TODO: this is called twice, once on opening an once on closing
718 document.getElementById("chatBtn").classList.remove("somethingnew");
720 processChat: function(chat) {
721 this.send("newchat", { data: chat });
722 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
723 if (this.game.type == "corr" && this.st.user.id > 0)
724 GameStorage.update(this.gameRef.id, { chat: chat });
726 gameOver: function(score, scoreMsg) {
727 this.game.score = score;
728 this.game.scoreMsg = this.st.tr[
729 scoreMsg ? scoreMsg : getScoreMessage(score)
731 const myIdx = this.game.players.findIndex(p => {
732 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
735 //OK, I play in this game
736 GameStorage.update(this.gameRef.id, {
740 // Notify the score to main Hall. TODO: only one player (currently double send)
741 this.send("result", { gid: this.game.id, score: score });
748 <style lang="sass" scoped>
750 background-color: lightgreen
762 @media screen and (min-width: 768px)
765 @media screen and (max-width: 767px)
770 display: inline-block
773 display: inline-block
776 @media screen and (max-width: 767px)
779 @media screen and (min-width: 768px)
796 display: inline-block
800 display: inline-block
811 .draw-sent, .draw-sent:hover
812 background-color: lightyellow
814 .draw-received, .draw-received:hover
815 background-color: lightgreen
817 .draw-threerep, .draw-threerep:hover
818 background-color: #e4d1fc
821 background-color: #c5fefe