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 { extractTime } from "@/utils/timeControl";
74 import { getRandString } from "@/utils/alea";
75 import { processModalClick } from "@/utils/modalClick";
76 import { getFullNotation } from "@/utils/notation";
77 import { playMove, getFilteredMove } from "@/utils/playUndo";
78 import { getScoreMessage } from "@/utils/scoring";
79 import params from "@/parameters";
86 // gameRef: to find the game in (potentially remote) storage
91 //given in URL (rid = remote ID)
97 players: [{ name: "" }, { name: "" }],
101 virtualClocks: [0, 0], //initialized with true game.clocks
102 vr: null, //"variant rules" object initialized from FEN
104 people: {}, //players + observers
105 lastate: undefined, //used if opponent send lastate before game is ready
106 repeat: {}, //detect position repetition
110 // Related to (killing of) self multi-connects:
116 $route: function(to) {
117 this.gameRef.id = to.params["id"];
118 this.gameRef.rid = to.query["rid"];
122 // NOTE: some redundant code with Hall.vue (mostly related to people array)
123 created: function() {
124 // Always add myself to players' list
125 const my = this.st.user;
126 this.$set(this.people, my.sid, { id: my.id, name: my.name });
127 this.gameRef.id = this.$route.params["id"];
128 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
129 // Initialize connection
130 this.connexionString =
137 encodeURIComponent(this.$route.path);
138 this.conn = new WebSocket(this.connexionString);
139 this.conn.onmessage = this.socketMessageListener;
140 this.conn.onclose = this.socketCloseListener;
141 // Socket init required before loading remote game:
142 const socketInit = callback => {
143 if (!!this.conn && this.conn.readyState == 1)
147 // Socket not ready yet (initial loading)
148 // NOTE: it's important to call callback without arguments,
149 // otherwise first arg is Websocket object and loadGame fails.
150 this.conn.onopen = () => {
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 // A more general approach would be to store it somewhere.
163 socketInit(this.loadGame);
166 mounted: function() {
168 .getElementById("chatWrap")
169 .addEventListener("click", processModalClick);
171 beforeDestroy: function() {
172 this.send("disconnect");
175 roomInit: function() {
176 // Notify the room only now that I connected, because
177 // messages might be lost otherwise (if game loading is slow)
178 this.send("connect");
179 this.send("pollclients");
181 send: function(code, obj) {
183 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
186 isConnected: function(index) {
187 const player = this.game.players[index];
189 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
191 // Try to find a match in people:
193 Object.keys(this.people).some(sid => sid == player.sid) ||
194 Object.values(this.people).some(p => p.id == player.uid)
197 resetChatColor: function() {
198 // TODO: this is called twice, once on opening an once on closing
199 document.getElementById("chatBtn").classList.remove("somethingnew");
201 processChat: function(chat) {
202 this.send("newchat", { data: chat });
203 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
204 if (this.game.type == "corr" && this.st.user.id > 0)
205 GameStorage.update(this.gameRef.id, { chat: chat });
207 clearChat: function() {
208 // Nothing more to do if game is live (chats not recorded)
209 if (this.game.mycolor && this.game.type == "corr") {
215 // TODO: this.game.pastChats = [] could be enough here?
216 this.$set(this.game, "pastChats", []);
221 socketMessageListener: function(msg) {
222 if (!this.conn) return;
223 const data = JSON.parse(msg.data);
226 data.sockIds.forEach(sid => {
227 this.$set(this.people, sid, { id: 0, name: "" });
228 if (sid != this.st.user.sid) {
229 this.send("askidentity", { target: sid });
230 // Ask potentially missed last state, if opponent and I play
232 !!this.game.mycolor &&
233 this.game.type == "live" &&
234 this.game.score == "*" &&
235 this.game.players.some(p => p.sid == sid)
237 this.send("asklastate", { target: sid });
243 if (!this.people[data.from])
244 this.$set(this.people, data.from, { name: "", id: 0 });
245 if (!this.people[data.from].name) {
246 this.newConnect[data.from] = true; //for self multi-connects tests
247 this.send("askidentity", { target: data.from });
251 this.$delete(this.people, data.from);
254 // I logged in elsewhere:
255 alert(this.st.tr["New connexion detected: tab now offline"]);
256 // TODO: this fails. See https://github.com/websockets/ws/issues/489
257 //this.conn.removeEventListener("message", this.socketMessageListener);
258 //this.conn.removeEventListener("close", this.socketCloseListener);
262 case "askidentity": {
263 // Request for identification (TODO: anonymous shouldn't need to reply)
265 // Decompose to avoid revealing email
266 name: this.st.user.name,
267 sid: this.st.user.sid,
270 this.send("identity", { data: me, target: data.from });
274 const user = data.data;
276 // If I multi-connect, kill current connexion if no mark (I'm older)
278 this.newConnect[user.sid] &&
280 user.id == this.st.user.id &&
281 user.sid != this.st.user.sid
283 if (!this.killed[this.st.user.sid]) {
284 this.send("killme", { sid: this.st.user.sid });
285 this.killed[this.st.user.sid] = true;
288 if (user.sid != this.st.user.sid) {
289 //I already know my identity...
290 this.$set(this.people, user.sid, {
296 delete this.newConnect[user.sid];
300 // Send current (live) game if not asked by any of the players
302 this.game.type == "live" &&
303 this.game.players.every(p => p.sid != data.from[0])
308 players: this.game.players,
310 cadence: this.game.cadence,
311 score: this.game.score,
312 rid: this.st.user.sid //useful in Hall if I'm an observer
314 this.send("game", { data: myGame, target: data.from });
318 this.send("fullgame", { data: this.game, target: data.from });
321 // Callback "roomInit" to poll clients only after game is loaded
322 let game = data.data;
323 // Move format isn't the same in storage and in browser,
324 // because of the 'addTime' field.
325 game.moves = game.moves.map(m => { return m.move || m; });
326 this.loadGame(game, this.roomInit);
329 // Sending last state if I played a move or score != "*"
331 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
332 this.game.score != "*" ||
333 this.drawOffer == "sent"
335 // Send our "last state" informations to opponent
336 const L = this.game.moves.length;
337 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
339 // NOTE: lastMove (when defined) includes addTime
340 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
341 // Since we played a move (or abort or resign),
342 // only drawOffer=="sent" is possible
343 drawSent: this.drawOffer == "sent",
344 score: this.game.score,
346 initime: this.game.initime[1 - myIdx] //relevant only if I played
348 this.send("lastate", { data: myLastate, target: data.from });
351 case "lastate": //got opponent infos about last move
352 this.lastate = data.data;
353 if (this.game.rendered)
354 // Game is rendered (Board component)
355 this.processLastate();
356 // Else: will be processed when game is ready
359 const move = data.data;
360 if (move.cancelDrawOffer) {
361 // Opponent refuses draw
363 // NOTE for corr games: drawOffer reset by player in turn
364 if (this.game.type == "live" && !!this.game.mycolor)
365 GameStorage.update(this.gameRef.id, { drawOffer: "" });
367 this.$refs["basegame"].play(
371 {addTime:move.addTime});
375 const score = data.side == "b" ? "1-0" : "0-1";
376 const side = data.side == "w" ? "White" : "Black";
377 this.gameOver(score, side + " surrender");
380 this.gameOver("?", "Stop");
383 this.gameOver("1/2", data.data);
386 // NOTE: observers don't know who offered draw
387 this.drawOffer = "received";
390 this.newChat = data.data;
391 if (!document.getElementById("modalChat").checked)
392 document.getElementById("chatBtn").classList.add("somethingnew");
396 socketCloseListener: function() {
397 this.conn = new WebSocket(this.connexionString);
398 this.conn.addEventListener("message", this.socketMessageListener);
399 this.conn.addEventListener("close", this.socketCloseListener);
401 // lastate was received, but maybe game wasn't ready yet:
402 processLastate: function() {
403 const data = this.lastate;
404 this.lastate = undefined; //security...
405 const L = this.game.moves.length;
406 if (data.movesCount > L) {
407 // Just got last move from him
408 this.$refs["basegame"].play(
412 {addTime:data.lastMove.addTime, initime:data.initime});
414 if (data.drawSent) this.drawOffer = "received";
415 if (data.score != "*") {
417 if (this.game.score == "*") this.gameOver(data.score);
420 clickDraw: function() {
421 if (!this.game.mycolor) return; //I'm just spectator
422 if (["received", "threerep"].includes(this.drawOffer)) {
423 if (!confirm(this.st.tr["Accept draw?"])) return;
425 this.drawOffer == "received"
427 : "Three repetitions";
428 this.send("draw", { data: message });
429 this.gameOver("1/2", message);
430 } else if (this.drawOffer == "") {
431 // No effect if drawOffer == "sent"
432 if (this.game.mycolor != this.vr.turn) {
433 alert(this.st.tr["Draw offer only in your turn"]);
436 if (!confirm(this.st.tr["Offer draw?"])) return;
437 this.drawOffer = "sent";
438 this.send("drawoffer");
439 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
442 abortGame: function() {
443 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
444 this.gameOver("?", "Stop");
448 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
450 this.send("resign", { data: this.game.mycolor });
451 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
452 const side = this.game.mycolor == "w" ? "White" : "Black";
453 this.gameOver(score, side + " surrender");
455 // 3 cases for loading a game:
456 // - from indexedDB (running or completed live game I play)
457 // - from server (one correspondance game I play[ed] or not)
458 // - from remote peer (one live game I don't play, finished or not)
459 loadGame: function(game, callback) {
460 const afterRetrieval = async game => {
461 const vModule = await import("@/variants/" + game.vname + ".js");
462 window.V = vModule.VariantRules;
463 this.vr = new V(game.fen);
464 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
465 const tc = extractTime(game.cadence);
466 const myIdx = game.players.findIndex(p => {
467 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
469 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
470 if (!game.chats) game.chats = []; //live games don't have chat history
471 if (gtype == "corr") {
472 if (game.players[0].color == "b") {
473 // Adopt the same convention for live and corr games: [0] = white
474 [game.players[0], game.players[1]] = [
479 // corr game: need to compute the clocks + initime
480 // NOTE: clocks in seconds, initime in milliseconds
481 game.clocks = [tc.mainTime, tc.mainTime];
482 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
483 const L = game.moves.length;
484 if (game.score == "*") {
485 // Set clocks + initime
486 game.initime = [0, 0];
488 let addTime = [0, 0];
489 for (let i = 2; i < L; i++) {
492 (game.moves[i].played - game.moves[i - 1].played) / 1000;
494 for (let i = 0; i <= 1; i++) game.clocks[i] += addTime[i];
496 if (L >= 1) game.initime[L % 2] = game.moves[L - 1].played;
498 // Sort chat messages from newest to oldest
499 game.chats.sort((c1, c2) => {
500 return c2.added - c1.added;
502 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
503 // Did a chat message arrive after my last move?
505 if (L == 1 && myIdx == 0)
506 dtLastMove = game.moves[0].played;
509 // It's now white turn
510 dtLastMove = game.moves[L-1-(1-myIdx)].played;
513 dtLastMove = game.moves[L-1-myIdx].played;
516 if (dtLastMove < game.chats[0].added)
517 document.getElementById("chatBtn").classList.add("somethingnew");
519 // Now that we used idx and played, re-format moves as for live games
520 game.moves = game.moves.map(m => m.squares);
522 if (gtype == "live" && game.clocks[0] < 0) {
524 game.clocks = [tc.mainTime, tc.mainTime];
525 if (game.score == "*") {
526 game.initime[0] = Date.now();
528 // I play in this live game; corr games don't have clocks+initime
529 GameStorage.update(game.id, {
531 initime: game.initime
536 if (game.drawOffer) {
537 if (game.drawOffer == "t")
539 this.drawOffer = "threerep";
541 // Draw offered by any of the players:
542 if (myIdx < 0) this.drawOffer = "received";
544 // I play in this game:
546 (game.drawOffer == "w" && myIdx == 0) ||
547 (game.drawOffer == "b" && myIdx == 1)
549 this.drawOffer = "sent";
550 else this.drawOffer = "received";
554 this.repeat = {}; //reset: scan past moves' FEN:
556 let vr_tmp = new V(game.fenStart);
558 game.moves.forEach(m => {
560 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
561 this.repeat[fenIdx] = this.repeat[fenIdx]
562 ? this.repeat[fenIdx] + 1
565 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
566 this.game = Object.assign(
567 // NOTE: assign mycolor here, since BaseGame could also be VS computer
570 increment: tc.increment,
572 // opponent sid not strictly required (or available), but easier
573 // at least oppsid or oppid is available anyway:
574 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
575 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
576 movesCount: game.moves.length
581 this.$nextTick(() => {
582 this.game.rendered = true;
583 // Did lastate arrive before game was rendered?
584 if (this.lastate) this.processLastate();
586 if (callback) callback();
589 afterRetrieval(game);
592 if (this.gameRef.rid) {
593 // Remote live game: forgetting about callback func... (TODO: design)
594 this.send("askfullgame", { target: this.gameRef.rid });
596 // Local or corr game
597 // NOTE: afterRetrieval() is never called if game not found
598 GameStorage.get(this.gameRef.id, afterRetrieval);
601 re_setClocks: function() {
602 if (this.game.movesCount < 2 || this.game.score != "*") {
603 // 1st move not completed yet, or game over: freeze time
604 this.virtualClocks = this.game.clocks.map(s => ppt(s));
607 const currentTurn = this.vr.turn;
608 const currentMovesCount = this.game.moves.length;
609 const colorIdx = ["w", "b"].indexOf(currentTurn);
611 this.game.clocks[colorIdx] -
612 (Date.now() - this.game.initime[colorIdx]) / 1000;
613 this.virtualClocks = [0, 1].map(i => {
615 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
616 return ppt(this.game.clocks[i] - removeTime);
618 let clockUpdate = setInterval(() => {
621 this.game.moves.length > currentMovesCount ||
622 this.game.score != "*"
624 clearInterval(clockUpdate);
627 currentTurn == "w" ? "0-1" : "1-0",
634 ppt(Math.max(0, --countdown))
638 // Post-process a (potentially partial) move (which was just played in BaseGame)
639 processMove: function(move, data) {
640 const moveCol = this.vr.turn;
641 const doProcessMove = () => {
642 const colorIdx = ["w", "b"].indexOf(moveCol);
643 const nextIdx = 1 - colorIdx;
644 if (this.game.mycolor) {
645 // NOTE: 'var' to see that variable outside this block
646 var filtered_move = getFilteredMove(move);
648 // Send move ("newmove" event) to people in the room (if our turn)
649 let addTime = data ? data.addTime : 0;
650 if (moveCol == this.game.mycolor) {
651 if (this.drawOffer == "received")
654 if (this.game.movesCount >= 2) {
655 const elapsed = Date.now() - this.game.initime[colorIdx];
656 // elapsed time is measured in milliseconds
657 addTime = this.game.increment - elapsed / 1000;
662 cancelDrawOffer: this.drawOffer == "",
663 // Players' SID required for /mygames page
664 // TODO: precompute and add this field to game object?
665 players: this.game.players.map(p => p.sid)
667 this.send("newmove", { data: sendMove });
669 // Update current game object (no need for moves stack):
670 playMove(move, this.vr);
671 this.game.movesCount++;
672 // (add)Time indication: useful in case of lastate infos requested
673 this.game.moves.push({move:move, addTime:addTime});
674 this.game.fen = this.vr.getFen();
675 this.game.clocks[colorIdx] += addTime;
676 // data.initime is set only when I receive a "lastate" move from opponent
677 this.game.initime[nextIdx] = (data && data.initime) ? data.initime : Date.now();
679 // If repetition detected, consider that a draw offer was received:
680 const fenObj = V.ParseFen(this.game.fen);
681 let repIdx = fenObj.position + "_" + fenObj.turn;
682 if (fenObj.flags) repIdx += "_" + fenObj.flags;
683 this.repeat[repIdx] = this.repeat[repIdx] ? this.repeat[repIdx] + 1 : 1;
684 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
685 else if (this.drawOffer == "threerep") this.drawOffer = "";
686 // Since corr games are stored at only one location, update should be
687 // done only by one player for each move:
690 (this.game.type == "live" || moveCol == this.game.mycolor)
693 switch (this.drawOffer) {
698 drawCode = this.game.mycolor;
701 drawCode = V.GetOppCol(this.game.mycolor);
704 if (this.game.type == "corr") {
705 GameStorage.update(this.gameRef.id, {
708 squares: filtered_move,
710 idx: this.game.moves.length - 1
712 // Code "n" for "None" to force reset (otherwise it's ignored)
713 drawOffer: drawCode || "n"
718 GameStorage.update(this.gameRef.id, {
721 clocks: this.game.clocks,
722 initime: this.game.initime,
728 if (this.game.type == "corr" && moveCol == this.game.mycolor) {
732 this.st.tr["Move played:"] +
734 getFullNotation(move) +
736 this.st.tr["Are you sure?"]
739 this.$refs["basegame"].cancelLastMove();
743 // Let small time to finish drawing current move attempt:
746 else doProcessMove();
748 gameOver: function(score, scoreMsg) {
749 this.game.score = score;
750 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
751 const myIdx = this.game.players.findIndex(p => {
752 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
755 // OK, I play in this game
756 GameStorage.update(this.gameRef.id, {
760 // Notify the score to main Hall. TODO: only one player (currently double send)
761 this.send("result", { gid: this.game.id, score: score });
768 <style lang="sass" scoped>
770 background-color: lightgreen
782 @media screen and (min-width: 768px)
785 @media screen and (max-width: 767px)
790 display: inline-block
793 display: inline-block
796 @media screen and (max-width: 767px)
799 @media screen and (min-width: 768px)
816 display: inline-block
820 display: inline-block
831 .draw-sent, .draw-sent:hover
832 background-color: lightyellow
834 .draw-received, .draw-received:hover
835 background-color: lightgreen
837 .draw-threerep, .draw-threerep:hover
838 background-color: #e4d1fc
841 background-color: #c5fefe