3 input#modalChat.modal(type="checkbox" @click="resetChatColor()")
4 div#chatWrap(role="dialog" data-checkbox="modalChat")
6 label.modal-close(for="modalChat")
8 span {{ Object.keys(people).length + " " + st.tr["participant(s):"] }}
9 span(v-for="p in Object.values(people)" v-if="!!p.name")
11 span.anonymous(v-if="Object.values(people).some(p => !p.name)")
13 Chat(:players="game.players" :pastChats="game.chats"
14 :newChat="newChat" @mychat="processChat")
16 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
17 span.variant-cadence {{ game.cadence }}
18 span.variant-name {{ game.vname }}
19 button#chatBtn(onClick="doClick('modalChat')") Chat
20 #actions(v-if="game.score=='*'")
21 button(@click="clickDraw()" :class="{['draw-' + drawOffer]: true}")
23 button(v-if="!!game.mycolor" @click="abortGame()") {{ st.tr["Abort"] }}
24 button(v-if="!!game.mycolor" @click="resign()") {{ st.tr["Resign"] }}
27 span.name(:class="{connected: isConnected(0)}")
28 | {{ game.players[0].name || "@nonymous" }}
29 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
31 span.name(:class="{connected: isConnected(1)}")
32 | {{ game.players[1].name || "@nonymous" }}
33 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
34 BaseGame(:game="game" :vr="vr" @newmove="processMove" @gameover="gameOver")
38 import BaseGame from "@/components/BaseGame.vue";
39 import Chat from "@/components/Chat.vue";
40 import { store } from "@/store";
41 import { GameStorage } from "@/utils/gameStorage";
42 import { ppt } from "@/utils/datetime";
43 import { extractTime } from "@/utils/timeControl";
44 import { getRandString } from "@/utils/alea";
45 import { processModalClick } from "@/utils/modalClick";
46 import { getScoreMessage } from "@/utils/scoring";
47 import params from "@/parameters";
54 // gameRef: to find the game in (potentially remote) storage
59 //given in URL (rid = remote ID)
65 players: [{ name: "" }, { name: "" }],
69 virtualClocks: [0, 0], //initialized with true game.clocks
70 vr: null, //"variant rules" object initialized from FEN
72 people: {}, //players + observers
73 lastate: undefined, //used if opponent send lastate before game is ready
74 repeat: {}, //detect position repetition
78 // Related to (killing of) self multi-connects:
84 $route: function(to) {
85 this.gameRef.id = to.params["id"];
86 this.gameRef.rid = to.query["rid"];
90 // NOTE: some redundant code with Hall.vue (mostly related to people array)
92 // Always add myself to players' list
93 const my = this.st.user;
94 this.$set(this.people, my.sid, { id: my.id, name: my.name });
95 this.gameRef.id = this.$route.params["id"];
96 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
97 // Initialize connection
98 this.connexionString =
105 encodeURIComponent(this.$route.path);
106 this.conn = new WebSocket(this.connexionString);
107 this.conn.onmessage = this.socketMessageListener;
108 this.conn.onclose = this.socketCloseListener;
109 // Socket init required before loading remote game:
110 const socketInit = callback => {
111 if (!!this.conn && this.conn.readyState == 1)
114 //socket not ready yet (initial loading)
116 // NOTE: it's important to call callback without arguments,
117 // otherwise first arg is Websocket object and loadGame fails.
118 this.conn.onopen = () => {
123 if (!this.gameRef.rid)
124 //game stored locally or on server
125 this.loadGame(null, () => socketInit(this.roomInit));
126 //game stored remotely: need socket to retrieve it
128 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
129 // --> It will be given when receiving "fullgame" socket event.
130 // A more general approach would be to store it somewhere.
131 socketInit(this.loadGame);
134 mounted: function() {
136 .getElementById("chatWrap")
137 .addEventListener("click", processModalClick);
139 beforeDestroy: function() {
140 this.send("disconnect");
143 roomInit: function() {
144 // Notify the room only now that I connected, because
145 // messages might be lost otherwise (if game loading is slow)
146 this.send("connect");
147 this.send("pollclients");
149 send: function(code, obj) {
151 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
154 isConnected: function(index) {
155 const player = this.game.players[index];
157 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
159 // Try to find a match in people:
161 Object.keys(this.people).some(sid => sid == player.sid) ||
162 Object.values(this.people).some(p => p.id == player.uid)
165 socketMessageListener: function(msg) {
166 if (!this.conn) return;
167 const data = JSON.parse(msg.data);
170 data.sockIds.forEach(sid => {
171 this.$set(this.people, sid, { id: 0, name: "" });
172 if (sid != this.st.user.sid) {
173 this.send("askidentity", { target: sid });
174 // Ask potentially missed last state, if opponent and I play
176 !!this.game.mycolor &&
177 this.game.type == "live" &&
178 this.game.score == "*" &&
179 this.game.players.some(p => p.sid == sid)
181 this.send("asklastate", { target: sid });
187 if (!this.people[data.from])
188 this.$set(this.people, data.from, { name: "", id: 0 });
189 if (!this.people[data.from].name) {
190 this.newConnect[data.from] = true; //for self multi-connects tests
191 this.send("askidentity", { target: data.from });
195 this.$delete(this.people, data.from);
198 // I logged in elsewhere:
199 alert(this.st.tr["New connexion detected: tab now offline"]);
200 // TODO: this fails. See https://github.com/websockets/ws/issues/489
201 //this.conn.removeEventListener("message", this.socketMessageListener);
202 //this.conn.removeEventListener("close", this.socketCloseListener);
206 case "askidentity": {
207 // Request for identification (TODO: anonymous shouldn't need to reply)
209 // Decompose to avoid revealing email
210 name: this.st.user.name,
211 sid: this.st.user.sid,
214 this.send("identity", { data: me, target: data.from });
218 const user = data.data;
220 //otherwise anonymous
221 // If I multi-connect, kill current connexion if no mark (I'm older)
223 this.newConnect[user.sid] &&
225 user.id == this.st.user.id &&
226 user.sid != this.st.user.sid
228 if (!this.killed[this.st.user.sid]) {
229 this.send("killme", { sid: this.st.user.sid });
230 this.killed[this.st.user.sid] = true;
233 if (user.sid != this.st.user.sid) {
234 //I already know my identity...
235 this.$set(this.people, user.sid, {
241 delete this.newConnect[user.sid];
245 // Send current (live) game if not asked by any of the players
247 this.game.type == "live" &&
248 this.game.players.every(p => p.sid != data.from[0])
253 players: this.game.players,
255 cadence: this.game.cadence,
256 score: this.game.score,
257 rid: this.st.user.sid //useful in Hall if I'm an observer
259 this.send("game", { data: myGame, target: data.from });
263 this.send("fullgame", { data: this.game, target: data.from });
266 // Callback "roomInit" to poll clients only after game is loaded
267 this.loadGame(data.data, this.roomInit);
270 // Sending last state if I played a move or score != "*"
272 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
273 this.game.score != "*" ||
274 this.drawOffer == "sent"
276 // Send our "last state" informations to opponent
277 const L = this.game.moves.length;
278 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
280 // NOTE: lastMove (when defined) includes addTime
281 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
282 // Since we played a move (or abort or resign),
283 // only drawOffer=="sent" is possible
284 drawSent: this.drawOffer == "sent",
285 score: this.game.score,
287 initime: this.game.initime[1 - myIdx] //relevant only if I played
289 this.send("lastate", { data: myLastate, target: data.from });
292 case "lastate": //got opponent infos about last move
293 this.lastate = data.data;
294 if (this.game.rendered)
295 //game is rendered (Board component)
296 this.processLastate();
297 //else: will be processed when game is ready
300 const move = data.data;
301 if (move.cancelDrawOffer) {
302 //opponent refuses draw
304 // NOTE for corr games: drawOffer reset by player in turn
305 if (this.game.type == "live" && !!this.game.mycolor)
306 GameStorage.update(this.gameRef.id, { drawOffer: "" });
308 this.$set(this.game, "moveToPlay", move);
312 this.gameOver(data.side == "b" ? "1-0" : "0-1", "Resign");
315 this.gameOver("?", "Abort");
318 this.gameOver("1/2", data.data);
321 // NOTE: observers don't know who offered draw
322 this.drawOffer = "received";
325 this.newChat = data.data;
326 if (!document.getElementById("modalChat").checked)
327 document.getElementById("chatBtn").classList.add("somethingnew");
331 socketCloseListener: function() {
332 this.conn = new WebSocket(this.connexionString);
333 this.conn.addEventListener("message", this.socketMessageListener);
334 this.conn.addEventListener("close", this.socketCloseListener);
336 // lastate was received, but maybe game wasn't ready yet:
337 processLastate: function() {
338 const data = this.lastate;
339 this.lastate = undefined; //security...
340 const L = this.game.moves.length;
341 if (data.movesCount > L) {
342 // Just got last move from him
346 Object.assign({ initime: data.initime }, data.lastMove)
349 if (data.drawSent) this.drawOffer = "received";
350 if (data.score != "*") {
352 if (this.game.score == "*") this.gameOver(data.score);
355 clickDraw: function() {
356 if (!this.game.mycolor) return; //I'm just spectator
357 if (["received", "threerep"].includes(this.drawOffer)) {
358 if (!confirm(this.st.tr["Accept draw?"])) return;
360 this.drawOffer == "received"
362 : "Three repetitions";
363 this.send("draw", { data: message });
364 this.gameOver("1/2", message);
365 } else if (this.drawOffer == "") {
366 //no effect if drawOffer == "sent"
367 if (this.game.mycolor != this.vr.turn) {
368 alert(this.st.tr["Draw offer only in your turn"]);
371 if (!confirm(this.st.tr["Offer draw?"])) return;
372 this.drawOffer = "sent";
373 this.send("drawoffer");
374 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
377 abortGame: function() {
378 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
379 this.gameOver("?", "Abort");
383 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
385 this.send("resign", { data: this.game.mycolor });
386 this.gameOver(this.game.mycolor == "w" ? "0-1" : "1-0", "Resign");
388 // 3 cases for loading a game:
389 // - from indexedDB (running or completed live game I play)
390 // - from server (one correspondance game I play[ed] or not)
391 // - from remote peer (one live game I don't play, finished or not)
392 loadGame: function(game, callback) {
393 const afterRetrieval = async game => {
394 const vModule = await import("@/variants/" + game.vname + ".js");
395 window.V = vModule.VariantRules;
396 this.vr = new V(game.fen);
397 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
398 const tc = extractTime(game.cadence);
399 const myIdx = game.players.findIndex(p => {
400 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
402 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
403 if (!game.chats) game.chats = []; //live games don't have chat history
404 if (gtype == "corr") {
405 if (game.players[0].color == "b") {
406 // Adopt the same convention for live and corr games: [0] = white
407 [game.players[0], game.players[1]] = [
412 // corr game: needs to compute the clocks + initime
413 // NOTE: clocks in seconds, initime in milliseconds
414 game.clocks = [tc.mainTime, tc.mainTime];
415 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
416 if (game.score == "*") {
417 //otherwise no need to bother with time
418 game.initime = [0, 0];
419 const L = game.moves.length;
421 let addTime = [0, 0];
422 for (let i = 2; i < L; i++) {
425 (game.moves[i].played - game.moves[i - 1].played) / 1000;
427 for (let i = 0; i <= 1; i++) game.clocks[i] += addTime[i];
429 if (L >= 1) game.initime[L % 2] = game.moves[L - 1].played;
431 const reformattedMoves = game.moves.map(m => {
440 // Sort chat messages from newest to oldest
441 game.chats.sort((c1, c2) => {
442 return c2.added - c1.added;
444 if (myIdx >= 0 && game.chats.length > 0) {
445 // TODO: group multi-moves into an array, to deduce color from index
446 // and not need this (also repeated in BaseGame::re_setVariables())
447 let vr_tmp = new V(game.fenStart); //vr is already at end of game
448 for (let i = 0; i < reformattedMoves.length; i++) {
449 game.moves[i].color = vr_tmp.turn;
450 vr_tmp.play(reformattedMoves[i]);
452 // Blue background on chat button if last chat message arrived after my last move.
454 for (let midx = game.moves.length - 1; midx >= 0; midx--) {
455 if (game.moves[midx].color == mycolor) {
456 dtLastMove = game.moves[midx].played;
460 if (dtLastMove < game.chats[0].added)
461 document.getElementById("chatBtn").classList.add("somethingnew");
463 // Now that we used idx and played, re-format moves as for live games
464 game.moves = reformattedMoves;
466 if (gtype == "live" && game.clocks[0] < 0) {
468 game.clocks = [tc.mainTime, tc.mainTime];
469 if (game.score == "*") {
470 game.initime[0] = Date.now();
472 // I play in this live game; corr games don't have clocks+initime
473 GameStorage.update(game.id, {
475 initime: game.initime
480 if (game.drawOffer) {
481 if (game.drawOffer == "t")
483 this.drawOffer = "threerep";
485 if (myIdx < 0) this.drawOffer = "received";
486 //by any of the players
488 // I play in this game:
490 (game.drawOffer == "w" && myIdx == 0) ||
491 (game.drawOffer == "b" && myIdx == 1)
493 this.drawOffer = "sent";
495 else this.drawOffer = "received";
499 if (game.scoreMsg) game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
500 this.game = Object.assign(
503 // NOTE: assign mycolor here, since BaseGame could also be VS computer
506 increment: tc.increment,
508 // opponent sid not strictly required (or available), but easier
509 // at least oppsid or oppid is available anyway:
510 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
511 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid
515 this.$nextTick(() => {
516 this.game.rendered = true;
517 // Did lastate arrive before game was rendered?
518 if (this.lastate) this.processLastate();
520 this.repeat = {}; //reset: scan past moves' FEN:
522 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
523 let vr_tmp = new V(game.fenStart);
524 game.moves.forEach(m => {
526 const fenObj = V.ParseFen(vr_tmp.getFen());
527 repIdx = fenObj.position + "_" + fenObj.turn;
528 if (fenObj.flags) repIdx += "_" + fenObj.flags;
529 this.repeat[repIdx] = this.repeat[repIdx]
530 ? this.repeat[repIdx] + 1
533 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
534 if (callback) callback();
537 afterRetrieval(game);
540 if (this.gameRef.rid) {
541 // Remote live game: forgetting about callback func... (TODO: design)
542 this.send("askfullgame", { target: this.gameRef.rid });
544 // Local or corr game
545 GameStorage.get(this.gameRef.id, afterRetrieval);
548 re_setClocks: function() {
549 if (this.game.moves.length < 2 || this.game.score != "*") {
550 // 1st move not completed yet, or game over: freeze time
551 this.virtualClocks = this.game.clocks.map(s => ppt(s));
554 const currentTurn = this.vr.turn;
555 const colorIdx = ["w", "b"].indexOf(currentTurn);
557 this.game.clocks[colorIdx] -
558 (Date.now() - this.game.initime[colorIdx]) / 1000;
559 this.virtualClocks = [0, 1].map(i => {
561 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
562 return ppt(this.game.clocks[i] - removeTime);
564 let clockUpdate = setInterval(() => {
567 this.vr.turn != currentTurn ||
568 this.game.score != "*"
570 clearInterval(clockUpdate);
573 this.vr.turn == "w" ? "0-1" : "1-0",
580 ppt(Math.max(0, --countdown))
584 // Post-process a move (which was just played in BaseGame)
585 processMove: function(move) {
586 if (this.game.type == "corr" && move.color == this.game.mycolor) {
589 this.st.tr["Move played:"] +
593 this.st.tr["Are you sure?"]
596 this.$set(this.game, "moveToUndo", move);
600 const colorIdx = ["w", "b"].indexOf(move.color);
601 const nextIdx = ["w", "b"].indexOf(this.vr.turn);
602 // https://stackoverflow.com/a/38750895
603 if (this.game.mycolor) {
604 const allowed_fields = ["appear", "vanish", "start", "end"];
605 // NOTE: 'var' to see this variable outside this block
606 var filtered_move = Object.keys(move)
607 .filter(key => allowed_fields.includes(key))
608 .reduce((obj, key) => {
609 obj[key] = move[key];
613 // Send move ("newmove" event) to people in the room (if our turn)
615 if (move.color == this.game.mycolor) {
616 if (this.drawOffer == "received")
619 if (this.game.moves.length >= 2) {
621 const elapsed = Date.now() - this.game.initime[colorIdx];
622 // elapsed time is measured in milliseconds
623 addTime = this.game.increment - elapsed / 1000;
625 const sendMove = Object.assign({}, filtered_move, {
627 cancelDrawOffer: this.drawOffer == ""
629 this.send("newmove", { data: sendMove });
630 // (Add)Time indication: useful in case of lastate infos requested
631 move.addTime = addTime;
632 } else addTime = move.addTime; //supposed transmitted
633 // Update current game object:
634 this.game.moves.push(move);
635 this.game.fen = move.fen;
636 this.game.clocks[colorIdx] += addTime;
637 // move.initime is set only when I receive a "lastate" move from opponent
638 this.game.initime[nextIdx] = move.initime || Date.now();
640 // If repetition detected, consider that a draw offer was received:
641 const fenObj = V.ParseFen(move.fen);
642 let repIdx = fenObj.position + "_" + fenObj.turn;
643 if (fenObj.flags) repIdx += "_" + fenObj.flags;
644 this.repeat[repIdx] = this.repeat[repIdx] ? this.repeat[repIdx] + 1 : 1;
645 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
646 else if (this.drawOffer == "threerep") this.drawOffer = "";
647 // Since corr games are stored at only one location, update should be
648 // done only by one player for each move:
650 !!this.game.mycolor &&
651 (this.game.type == "live" || move.color == this.game.mycolor)
654 switch (this.drawOffer) {
659 drawCode = this.game.mycolor;
662 drawCode = this.vr.turn;
665 if (this.game.type == "corr") {
666 GameStorage.update(this.gameRef.id, {
669 squares: filtered_move,
671 idx: this.game.moves.length - 1
673 drawOffer: drawCode || "n" //"n" for "None" to force reset (otherwise it's ignored)
677 GameStorage.update(this.gameRef.id, {
680 clocks: this.game.clocks,
681 initime: this.game.initime,
687 resetChatColor: function() {
688 // TODO: this is called twice, once on opening an once on closing
689 document.getElementById("chatBtn").classList.remove("somethingnew");
691 processChat: function(chat) {
692 this.send("newchat", { data: chat });
693 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
694 if (this.game.type == "corr" && this.st.user.id > 0)
695 GameStorage.update(this.gameRef.id, { chat: chat });
697 gameOver: function(score, scoreMsg) {
698 this.game.score = score;
699 this.game.scoreMsg = this.st.tr[
700 scoreMsg ? scoreMsg : getScoreMessage(score)
702 const myIdx = this.game.players.findIndex(p => {
703 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
706 //OK, I play in this game
707 GameStorage.update(this.gameRef.id, {
711 // Notify the score to main Hall. TODO: only one player (currently double send)
712 this.send("result", { gid: this.game.id, score: score });
719 <style lang="sass" scoped>
721 background-color: lightgreen
733 @media screen and (min-width: 768px)
736 @media screen and (max-width: 767px)
741 display: inline-block
744 display: inline-block
747 @media screen and (max-width: 767px)
750 @media screen and (min-width: 768px)
767 display: inline-block
771 display: inline-block
782 .draw-sent, .draw-sent:hover
783 background-color: lightyellow
785 .draw-received, .draw-received:hover
786 background-color: lightgreen
788 .draw-threerep, .draw-threerep:hover
789 background-color: #e4d1fc
792 background-color: #c5fefe