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] }}
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 { extractTime } from "@/utils/timeControl";
74 import { getRandString } from "@/utils/alea";
75 import { processModalClick } from "@/utils/modalClick";
76 import { getScoreMessage } from "@/utils/scoring";
77 import params from "@/parameters";
84 // gameRef: to find the game in (potentially remote) storage
89 //given in URL (rid = remote ID)
95 players: [{ name: "" }, { name: "" }],
99 virtualClocks: [0, 0], //initialized with true game.clocks
100 vr: null, //"variant rules" object initialized from FEN
102 people: {}, //players + observers
103 lastate: undefined, //used if opponent send lastate before game is ready
104 repeat: {}, //detect position repetition
108 // Related to (killing of) self multi-connects:
114 $route: function(to) {
115 this.gameRef.id = to.params["id"];
116 this.gameRef.rid = to.query["rid"];
120 // NOTE: some redundant code with Hall.vue (mostly related to people array)
121 created: function() {
122 // Always add myself to players' list
123 const my = this.st.user;
124 this.$set(this.people, my.sid, { id: my.id, name: my.name });
125 this.gameRef.id = this.$route.params["id"];
126 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
127 // Initialize connection
128 this.connexionString =
135 encodeURIComponent(this.$route.path);
136 this.conn = new WebSocket(this.connexionString);
137 this.conn.onmessage = this.socketMessageListener;
138 this.conn.onclose = this.socketCloseListener;
139 // Socket init required before loading remote game:
140 const socketInit = callback => {
141 if (!!this.conn && this.conn.readyState == 1)
145 // Socket not ready yet (initial loading)
146 // NOTE: it's important to call callback without arguments,
147 // otherwise first arg is Websocket object and loadGame fails.
148 this.conn.onopen = () => {
153 if (!this.gameRef.rid)
154 // Game stored locally or on server
155 this.loadGame(null, () => socketInit(this.roomInit));
157 // Game stored remotely: need socket to retrieve it
158 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
159 // --> It will be given when receiving "fullgame" socket event.
160 // A more general approach would be to store it somewhere.
161 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)));
184 isConnected: function(index) {
185 const player = this.game.players[index];
187 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
189 // Try to find a match in people:
191 Object.keys(this.people).some(sid => sid == player.sid) ||
192 Object.values(this.people).some(p => p.id == player.uid)
195 socketMessageListener: function(msg) {
196 if (!this.conn) return;
197 const data = JSON.parse(msg.data);
200 data.sockIds.forEach(sid => {
201 this.$set(this.people, sid, { id: 0, name: "" });
202 if (sid != this.st.user.sid) {
203 this.send("askidentity", { target: sid });
204 // Ask potentially missed last state, if opponent and I play
206 !!this.game.mycolor &&
207 this.game.type == "live" &&
208 this.game.score == "*" &&
209 this.game.players.some(p => p.sid == sid)
211 this.send("asklastate", { target: sid });
217 if (!this.people[data.from])
218 this.$set(this.people, data.from, { name: "", id: 0 });
219 if (!this.people[data.from].name) {
220 this.newConnect[data.from] = true; //for self multi-connects tests
221 this.send("askidentity", { target: data.from });
225 this.$delete(this.people, data.from);
228 // I logged in elsewhere:
229 alert(this.st.tr["New connexion detected: tab now offline"]);
230 // TODO: this fails. See https://github.com/websockets/ws/issues/489
231 //this.conn.removeEventListener("message", this.socketMessageListener);
232 //this.conn.removeEventListener("close", this.socketCloseListener);
236 case "askidentity": {
237 // Request for identification (TODO: anonymous shouldn't need to reply)
239 // Decompose to avoid revealing email
240 name: this.st.user.name,
241 sid: this.st.user.sid,
244 this.send("identity", { data: me, target: data.from });
248 const user = data.data;
250 // If I multi-connect, kill current connexion if no mark (I'm older)
252 this.newConnect[user.sid] &&
254 user.id == this.st.user.id &&
255 user.sid != this.st.user.sid
257 if (!this.killed[this.st.user.sid]) {
258 this.send("killme", { sid: this.st.user.sid });
259 this.killed[this.st.user.sid] = true;
262 if (user.sid != this.st.user.sid) {
263 //I already know my identity...
264 this.$set(this.people, user.sid, {
270 delete this.newConnect[user.sid];
274 // Send current (live) game if not asked by any of the players
276 this.game.type == "live" &&
277 this.game.players.every(p => p.sid != data.from[0])
282 players: this.game.players,
284 cadence: this.game.cadence,
285 score: this.game.score,
286 rid: this.st.user.sid //useful in Hall if I'm an observer
288 this.send("game", { data: myGame, target: data.from });
292 this.send("fullgame", { data: this.game, target: data.from });
295 // Callback "roomInit" to poll clients only after game is loaded
296 this.loadGame(data.data, this.roomInit);
299 // Sending last state if I played a move or score != "*"
301 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
302 this.game.score != "*" ||
303 this.drawOffer == "sent"
305 // Send our "last state" informations to opponent
306 const L = this.game.moves.length;
307 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
309 // NOTE: lastMove (when defined) includes addTime
310 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
311 // Since we played a move (or abort or resign),
312 // only drawOffer=="sent" is possible
313 drawSent: this.drawOffer == "sent",
314 score: this.game.score,
316 initime: this.game.initime[1 - myIdx] //relevant only if I played
318 this.send("lastate", { data: myLastate, target: data.from });
321 case "lastate": //got opponent infos about last move
322 this.lastate = data.data;
323 if (this.game.rendered)
324 //game is rendered (Board component)
325 this.processLastate();
326 //else: will be processed when game is ready
329 const move = data.data;
330 if (move.cancelDrawOffer) {
331 //opponent refuses draw
333 // NOTE for corr games: drawOffer reset by player in turn
334 if (this.game.type == "live" && !!this.game.mycolor)
335 GameStorage.update(this.gameRef.id, { drawOffer: "" });
337 this.$refs["basegame"].play(move, "received");
341 const score = data.side == "b" ? "1-0" : "0-1";
342 const side = data.side == "w" ? "White" : "Black";
343 this.gameOver(score, side + " surrender");
346 this.gameOver("?", "Stop");
349 this.gameOver("1/2", data.data);
352 // NOTE: observers don't know who offered draw
353 this.drawOffer = "received";
356 this.newChat = data.data;
357 if (!document.getElementById("modalChat").checked)
358 document.getElementById("chatBtn").classList.add("somethingnew");
362 socketCloseListener: function() {
363 this.conn = new WebSocket(this.connexionString);
364 this.conn.addEventListener("message", this.socketMessageListener);
365 this.conn.addEventListener("close", this.socketCloseListener);
367 // lastate was received, but maybe game wasn't ready yet:
368 processLastate: function() {
369 const data = this.lastate;
370 this.lastate = undefined; //security...
371 const L = this.game.moves.length;
372 if (data.movesCount > L) {
373 // Just got last move from him
374 this.$refs["basegame"].play(
375 Object.assign({ initime: data.initime }, data.lastMove)
378 if (data.drawSent) this.drawOffer = "received";
379 if (data.score != "*") {
381 if (this.game.score == "*") this.gameOver(data.score);
384 clickDraw: function() {
385 if (!this.game.mycolor) return; //I'm just spectator
386 if (["received", "threerep"].includes(this.drawOffer)) {
387 if (!confirm(this.st.tr["Accept draw?"])) return;
389 this.drawOffer == "received"
391 : "Three repetitions";
392 this.send("draw", { data: message });
393 this.gameOver("1/2", message);
394 } else if (this.drawOffer == "") {
395 //no effect if drawOffer == "sent"
396 if (this.game.mycolor != this.vr.turn) {
397 alert(this.st.tr["Draw offer only in your turn"]);
400 if (!confirm(this.st.tr["Offer draw?"])) return;
401 this.drawOffer = "sent";
402 this.send("drawoffer");
403 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
406 abortGame: function() {
407 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
408 this.gameOver("?", "Stop");
412 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
414 this.send("resign", { data: this.game.mycolor });
415 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
416 const side = this.game.mycolor == "w" ? "White" : "Black";
417 this.gameOver(score, side + " surrender");
419 // 3 cases for loading a game:
420 // - from indexedDB (running or completed live game I play)
421 // - from server (one correspondance game I play[ed] or not)
422 // - from remote peer (one live game I don't play, finished or not)
423 loadGame: function(game, callback) {
424 const afterRetrieval = async game => {
425 const vModule = await import("@/variants/" + game.vname + ".js");
426 window.V = vModule.VariantRules;
427 this.vr = new V(game.fen);
428 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
429 const tc = extractTime(game.cadence);
430 const myIdx = game.players.findIndex(p => {
431 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
433 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
434 if (!game.chats) game.chats = []; //live games don't have chat history
435 if (gtype == "corr") {
436 if (game.players[0].color == "b") {
437 // Adopt the same convention for live and corr games: [0] = white
438 [game.players[0], game.players[1]] = [
443 // corr game: need to compute the clocks + initime
444 // NOTE: clocks in seconds, initime in milliseconds
445 game.clocks = [tc.mainTime, tc.mainTime];
446 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
447 if (game.score == "*") {
448 //otherwise no need to bother with time
449 game.initime = [0, 0];
450 const L = game.moves.length;
452 let addTime = [0, 0];
453 for (let i = 2; i < L; i++) {
456 (game.moves[i].played - game.moves[i - 1].played) / 1000;
458 for (let i = 0; i <= 1; i++) game.clocks[i] += addTime[i];
460 if (L >= 1) game.initime[L % 2] = game.moves[L - 1].played;
462 // Sort chat messages from newest to oldest
463 game.chats.sort((c1, c2) => {
464 return c2.added - c1.added;
466 if (myIdx >= 0 && game.chats.length > 0) {
467 // Did a chat message arrive after my last move?
468 let vr_tmp = new V(game.fen); //start from last position
469 const flags = V.ParseFen(game.fen).flags; //may be undefined
471 for (let midx = game.moves.length - 1; midx >= 0; midx--) {
472 vr_tmp.undo(Object.assign({flags:flags}, game.moves[midx].squares));
473 if (vr_tmp.turn == mycolor) {
474 dtLastMove = game.moves[midx].played;
478 if (dtLastMove < game.chats[0].added)
479 document.getElementById("chatBtn").classList.add("somethingnew");
481 // Now that we used idx and played, re-format moves as for live games
482 game.moves = game.moves.map(m => m.squares);
484 if (gtype == "live" && game.clocks[0] < 0) {
486 game.clocks = [tc.mainTime, tc.mainTime];
487 if (game.score == "*") {
488 game.initime[0] = Date.now();
490 // I play in this live game; corr games don't have clocks+initime
491 GameStorage.update(game.id, {
493 initime: game.initime
498 if (game.drawOffer) {
499 if (game.drawOffer == "t")
501 this.drawOffer = "threerep";
503 // Draw offered by any of the players:
504 if (myIdx < 0) this.drawOffer = "received";
506 // I play in this game:
508 (game.drawOffer == "w" && myIdx == 0) ||
509 (game.drawOffer == "b" && myIdx == 1)
511 this.drawOffer = "sent";
512 else this.drawOffer = "received";
516 this.repeat = {}; //reset: scan past moves' FEN:
518 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
519 let vr_tmp = new V(game.fenStart);
522 game.moves.forEach(m => {
523 if (vr_tmp.turn != curTurn)
526 curTurn = vr_tmp.turn;
529 const fenObj = V.ParseFen(vr_tmp.getFen());
530 repIdx = fenObj.position + "_" + fenObj.turn;
531 if (fenObj.flags) repIdx += "_" + fenObj.flags;
532 this.repeat[repIdx] = this.repeat[repIdx]
533 ? this.repeat[repIdx] + 1
536 if (vr_tmp.turn != curTurn)
538 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
539 this.game = Object.assign(
542 // NOTE: assign mycolor here, since BaseGame could also be VS computer
545 increment: tc.increment,
547 // opponent sid not strictly required (or available), but easier
548 // at least oppsid or oppid is available anyway:
549 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
550 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
551 movesCount: movesCount,
555 this.$nextTick(() => {
556 this.game.rendered = true;
557 // Did lastate arrive before game was rendered?
558 if (this.lastate) this.processLastate();
560 if (callback) callback();
563 afterRetrieval(game);
566 if (this.gameRef.rid) {
567 // Remote live game: forgetting about callback func... (TODO: design)
568 this.send("askfullgame", { target: this.gameRef.rid });
570 // Local or corr game
571 // NOTE: afterRetrieval() is never called if game not found
572 GameStorage.get(this.gameRef.id, afterRetrieval);
575 re_setClocks: function() {
576 if (this.game.movesCount < 2 || this.game.score != "*") {
577 // 1st move not completed yet, or game over: freeze time
578 this.virtualClocks = this.game.clocks.map(s => ppt(s));
581 const currentTurn = this.vr.turn;
582 const currentMovesCount = this.game.moves.length;
583 const colorIdx = ["w", "b"].indexOf(currentTurn);
585 this.game.clocks[colorIdx] -
586 (Date.now() - this.game.initime[colorIdx]) / 1000;
587 this.virtualClocks = [0, 1].map(i => {
589 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
590 return ppt(this.game.clocks[i] - removeTime);
592 let clockUpdate = setInterval(() => {
595 this.game.moves.length > currentMovesCount ||
596 this.game.score != "*"
598 clearInterval(clockUpdate);
601 currentTurn == "w" ? "0-1" : "1-0",
608 ppt(Math.max(0, --countdown))
612 // Post-process a (potentially partial) move (which was just played in BaseGame)
613 processMove: function(move) {
614 if (this.game.type == "corr" && move.color == this.game.mycolor) {
617 this.st.tr["Move played:"] +
621 this.st.tr["Are you sure?"]
624 this.$refs["basegame"].undo(move);
628 const colorIdx = ["w", "b"].indexOf(move.color);
629 const nextIdx = ["w", "b"].indexOf(this.vr.turn);
630 // https://stackoverflow.com/a/38750895
631 if (this.game.mycolor) {
632 const allowed_fields = ["appear", "vanish", "start", "end"];
633 // NOTE: 'var' to see that variable outside this block
634 var filtered_move = Object.keys(move)
635 .filter(key => allowed_fields.includes(key))
636 .reduce((obj, key) => {
637 obj[key] = move[key];
641 // Send move ("newmove" event) to people in the room (if our turn)
643 if (move.color == this.game.mycolor) {
644 if (this.drawOffer == "received")
647 if (this.game.movesCount >= 2) {
648 const elapsed = Date.now() - this.game.initime[colorIdx];
649 // elapsed time is measured in milliseconds
650 addTime = this.game.increment - elapsed / 1000;
652 const sendMove = Object.assign({}, filtered_move, {
654 cancelDrawOffer: this.drawOffer == ""
656 this.send("newmove", { data: sendMove });
657 // (Add)Time indication: useful in case of lastate infos requested
658 move.addTime = addTime;
659 } else addTime = move.addTime; //supposed transmitted
660 // Update current game object:
661 if (nextIdx != colorIdx)
662 this.game.movesCount++;
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:
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 // Code "n" for "None" to force reset (otherwise it's ignored)
703 drawOffer: drawCode || "n"
708 GameStorage.update(this.gameRef.id, {
711 clocks: this.game.clocks,
712 initime: this.game.initime,
718 resetChatColor: function() {
719 // TODO: this is called twice, once on opening an once on closing
720 document.getElementById("chatBtn").classList.remove("somethingnew");
722 processChat: function(chat) {
723 this.send("newchat", { data: chat });
724 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
725 if (this.game.type == "corr" && this.st.user.id > 0)
726 GameStorage.update(this.gameRef.id, { chat: chat });
728 gameOver: function(score, scoreMsg) {
729 this.game.score = score;
730 this.$set(this.game, "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