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 { getFullNotation } from "@/utils/notation";
76 import { playMove, getFilteredMove } from "@/utils/playUndo";
77 import { getScoreMessage } from "@/utils/scoring";
78 import params from "@/parameters";
85 // gameRef: to find the game in (potentially remote) storage
90 //given in URL (rid = remote ID)
96 players: [{ name: "" }, { name: "" }],
100 virtualClocks: [0, 0], //initialized with true game.clocks
101 vr: null, //"variant rules" object initialized from FEN
103 people: {}, //players + observers
104 lastate: undefined, //used if opponent send lastate before game is ready
105 repeat: {}, //detect position repetition
109 // Related to (killing of) self multi-connects:
115 $route: function(to) {
116 this.gameRef.id = to.params["id"];
117 this.gameRef.rid = to.query["rid"];
121 // NOTE: some redundant code with Hall.vue (mostly related to people array)
122 created: function() {
123 // Always add myself to players' list
124 const my = this.st.user;
125 this.$set(this.people, my.sid, { id: my.id, name: my.name });
126 this.gameRef.id = this.$route.params["id"];
127 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
128 // Initialize connection
129 this.connexionString =
136 encodeURIComponent(this.$route.path);
137 this.conn = new WebSocket(this.connexionString);
138 this.conn.onmessage = this.socketMessageListener;
139 this.conn.onclose = this.socketCloseListener;
140 // Socket init required before loading remote game:
141 const socketInit = callback => {
142 if (!!this.conn && this.conn.readyState == 1)
146 // Socket not ready yet (initial loading)
147 // NOTE: it's important to call callback without arguments,
148 // otherwise first arg is Websocket object and loadGame fails.
149 this.conn.onopen = () => {
154 if (!this.gameRef.rid)
155 // Game stored locally or on server
156 this.loadGame(null, () => socketInit(this.roomInit));
158 // Game stored remotely: need socket to retrieve it
159 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
160 // --> It will be given when receiving "fullgame" socket event.
161 // A more general approach would be to store it somewhere.
162 socketInit(this.loadGame);
165 mounted: function() {
167 .getElementById("chatWrap")
168 .addEventListener("click", processModalClick);
170 beforeDestroy: function() {
171 this.send("disconnect");
174 roomInit: function() {
175 // Notify the room only now that I connected, because
176 // messages might be lost otherwise (if game loading is slow)
177 this.send("connect");
178 this.send("pollclients");
180 send: function(code, obj) {
182 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
185 isConnected: function(index) {
186 const player = this.game.players[index];
188 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
190 // Try to find a match in people:
192 Object.keys(this.people).some(sid => sid == player.sid) ||
193 Object.values(this.people).some(p => p.id == player.uid)
196 socketMessageListener: function(msg) {
197 if (!this.conn) return;
198 const data = JSON.parse(msg.data);
201 data.sockIds.forEach(sid => {
202 this.$set(this.people, sid, { id: 0, name: "" });
203 if (sid != this.st.user.sid) {
204 this.send("askidentity", { target: sid });
205 // Ask potentially missed last state, if opponent and I play
207 !!this.game.mycolor &&
208 this.game.type == "live" &&
209 this.game.score == "*" &&
210 this.game.players.some(p => p.sid == sid)
212 this.send("asklastate", { target: sid });
218 if (!this.people[data.from])
219 this.$set(this.people, data.from, { name: "", id: 0 });
220 if (!this.people[data.from].name) {
221 this.newConnect[data.from] = true; //for self multi-connects tests
222 this.send("askidentity", { target: data.from });
226 this.$delete(this.people, data.from);
229 // I logged in elsewhere:
230 alert(this.st.tr["New connexion detected: tab now offline"]);
231 // TODO: this fails. See https://github.com/websockets/ws/issues/489
232 //this.conn.removeEventListener("message", this.socketMessageListener);
233 //this.conn.removeEventListener("close", this.socketCloseListener);
237 case "askidentity": {
238 // Request for identification (TODO: anonymous shouldn't need to reply)
240 // Decompose to avoid revealing email
241 name: this.st.user.name,
242 sid: this.st.user.sid,
245 this.send("identity", { data: me, target: data.from });
249 const user = data.data;
251 // If I multi-connect, kill current connexion if no mark (I'm older)
253 this.newConnect[user.sid] &&
255 user.id == this.st.user.id &&
256 user.sid != this.st.user.sid
258 if (!this.killed[this.st.user.sid]) {
259 this.send("killme", { sid: this.st.user.sid });
260 this.killed[this.st.user.sid] = true;
263 if (user.sid != this.st.user.sid) {
264 //I already know my identity...
265 this.$set(this.people, user.sid, {
271 delete this.newConnect[user.sid];
275 // Send current (live) game if not asked by any of the players
277 this.game.type == "live" &&
278 this.game.players.every(p => p.sid != data.from[0])
283 players: this.game.players,
285 cadence: this.game.cadence,
286 score: this.game.score,
287 rid: this.st.user.sid //useful in Hall if I'm an observer
289 this.send("game", { data: myGame, target: data.from });
293 this.send("fullgame", { data: this.game, target: data.from });
296 // Callback "roomInit" to poll clients only after game is loaded
297 this.loadGame(data.data, this.roomInit);
300 // Sending last state if I played a move or score != "*"
302 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
303 this.game.score != "*" ||
304 this.drawOffer == "sent"
306 // Send our "last state" informations to opponent
307 const L = this.game.moves.length;
308 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
310 // NOTE: lastMove (when defined) includes addTime
311 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
312 // Since we played a move (or abort or resign),
313 // only drawOffer=="sent" is possible
314 drawSent: this.drawOffer == "sent",
315 score: this.game.score,
317 initime: this.game.initime[1 - myIdx] //relevant only if I played
319 this.send("lastate", { data: myLastate, target: data.from });
322 case "lastate": //got opponent infos about last move
323 this.lastate = data.data;
324 if (this.game.rendered)
325 // Game is rendered (Board component)
326 this.processLastate();
327 // Else: will be processed when game is ready
330 const move = data.data;
331 if (move.cancelDrawOffer) {
332 // Opponent refuses draw
334 // NOTE for corr games: drawOffer reset by player in turn
335 if (this.game.type == "live" && !!this.game.mycolor)
336 GameStorage.update(this.gameRef.id, { drawOffer: "" });
338 this.$refs["basegame"].play(
342 {addTime:move.addTime});
346 const score = data.side == "b" ? "1-0" : "0-1";
347 const side = data.side == "w" ? "White" : "Black";
348 this.gameOver(score, side + " surrender");
351 this.gameOver("?", "Stop");
354 this.gameOver("1/2", data.data);
357 // NOTE: observers don't know who offered draw
358 this.drawOffer = "received";
361 this.newChat = data.data;
362 if (!document.getElementById("modalChat").checked)
363 document.getElementById("chatBtn").classList.add("somethingnew");
367 socketCloseListener: function() {
368 this.conn = new WebSocket(this.connexionString);
369 this.conn.addEventListener("message", this.socketMessageListener);
370 this.conn.addEventListener("close", this.socketCloseListener);
372 // lastate was received, but maybe game wasn't ready yet:
373 processLastate: function() {
374 const data = this.lastate;
375 this.lastate = undefined; //security...
376 const L = this.game.moves.length;
377 if (data.movesCount > L) {
378 // Just got last move from him
379 this.$refs["basegame"].play(
383 {addTime:data.lastMove.addTime, initime:data.initime});
385 if (data.drawSent) this.drawOffer = "received";
386 if (data.score != "*") {
388 if (this.game.score == "*") this.gameOver(data.score);
391 clickDraw: function() {
392 if (!this.game.mycolor) return; //I'm just spectator
393 if (["received", "threerep"].includes(this.drawOffer)) {
394 if (!confirm(this.st.tr["Accept draw?"])) return;
396 this.drawOffer == "received"
398 : "Three repetitions";
399 this.send("draw", { data: message });
400 this.gameOver("1/2", message);
401 } else if (this.drawOffer == "") {
402 // No effect if drawOffer == "sent"
403 if (this.game.mycolor != this.vr.turn) {
404 alert(this.st.tr["Draw offer only in your turn"]);
407 if (!confirm(this.st.tr["Offer draw?"])) return;
408 this.drawOffer = "sent";
409 this.send("drawoffer");
410 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
413 abortGame: function() {
414 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
415 this.gameOver("?", "Stop");
419 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
421 this.send("resign", { data: this.game.mycolor });
422 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
423 const side = this.game.mycolor == "w" ? "White" : "Black";
424 this.gameOver(score, side + " surrender");
426 // 3 cases for loading a game:
427 // - from indexedDB (running or completed live game I play)
428 // - from server (one correspondance game I play[ed] or not)
429 // - from remote peer (one live game I don't play, finished or not)
430 loadGame: function(game, callback) {
431 const afterRetrieval = async game => {
432 const vModule = await import("@/variants/" + game.vname + ".js");
433 window.V = vModule.VariantRules;
434 this.vr = new V(game.fen);
435 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
436 const tc = extractTime(game.cadence);
437 const myIdx = game.players.findIndex(p => {
438 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
440 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
441 if (!game.chats) game.chats = []; //live games don't have chat history
442 if (gtype == "corr") {
443 if (game.players[0].color == "b") {
444 // Adopt the same convention for live and corr games: [0] = white
445 [game.players[0], game.players[1]] = [
450 // corr game: need to compute the clocks + initime
451 // NOTE: clocks in seconds, initime in milliseconds
452 game.clocks = [tc.mainTime, tc.mainTime];
453 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
454 const L = game.moves.length;
455 if (game.score == "*") {
456 // Set clocks + initime
457 game.initime = [0, 0];
459 let addTime = [0, 0];
460 for (let i = 2; i < L; i++) {
463 (game.moves[i].played - game.moves[i - 1].played) / 1000;
465 for (let i = 0; i <= 1; i++) game.clocks[i] += addTime[i];
467 if (L >= 1) game.initime[L % 2] = game.moves[L - 1].played;
469 // Sort chat messages from newest to oldest
470 game.chats.sort((c1, c2) => {
471 return c2.added - c1.added;
473 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
474 // Did a chat message arrive after my last move?
476 if (L == 1 && myIdx == 0)
477 dtLastMove = game.moves[0].played;
480 // It's now white turn
481 dtLastMove = game.moves[L-1-(1-myIdx)].played;
484 dtLastMove = game.moves[L-1-myIdx].played;
487 if (dtLastMove < game.chats[0].added)
488 document.getElementById("chatBtn").classList.add("somethingnew");
490 // Now that we used idx and played, re-format moves as for live games
491 game.moves = game.moves.map(m => m.squares);
493 if (gtype == "live" && game.clocks[0] < 0) {
495 game.clocks = [tc.mainTime, tc.mainTime];
496 if (game.score == "*") {
497 game.initime[0] = Date.now();
499 // I play in this live game; corr games don't have clocks+initime
500 GameStorage.update(game.id, {
502 initime: game.initime
507 if (game.drawOffer) {
508 if (game.drawOffer == "t")
510 this.drawOffer = "threerep";
512 // Draw offered by any of the players:
513 if (myIdx < 0) this.drawOffer = "received";
515 // I play in this game:
517 (game.drawOffer == "w" && myIdx == 0) ||
518 (game.drawOffer == "b" && myIdx == 1)
520 this.drawOffer = "sent";
521 else this.drawOffer = "received";
525 this.repeat = {}; //reset: scan past moves' FEN:
527 let vr_tmp = new V(game.fenStart);
529 game.moves.forEach(m => {
531 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
532 this.repeat[fenIdx] = this.repeat[fenIdx]
533 ? this.repeat[fenIdx] + 1
536 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
537 this.game = Object.assign(
538 // NOTE: assign mycolor here, since BaseGame could also be VS computer
541 increment: tc.increment,
543 // opponent sid not strictly required (or available), but easier
544 // at least oppsid or oppid is available anyway:
545 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
546 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
547 movesCount: game.moves.length
552 this.$nextTick(() => {
553 this.game.rendered = true;
554 // Did lastate arrive before game was rendered?
555 if (this.lastate) this.processLastate();
557 if (callback) callback();
560 afterRetrieval(game);
563 if (this.gameRef.rid) {
564 // Remote live game: forgetting about callback func... (TODO: design)
565 this.send("askfullgame", { target: this.gameRef.rid });
567 // Local or corr game
568 // NOTE: afterRetrieval() is never called if game not found
569 GameStorage.get(this.gameRef.id, afterRetrieval);
572 re_setClocks: function() {
573 if (this.game.movesCount < 2 || this.game.score != "*") {
574 // 1st move not completed yet, or game over: freeze time
575 this.virtualClocks = this.game.clocks.map(s => ppt(s));
578 const currentTurn = this.vr.turn;
579 const currentMovesCount = this.game.moves.length;
580 const colorIdx = ["w", "b"].indexOf(currentTurn);
582 this.game.clocks[colorIdx] -
583 (Date.now() - this.game.initime[colorIdx]) / 1000;
584 this.virtualClocks = [0, 1].map(i => {
586 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
587 return ppt(this.game.clocks[i] - removeTime);
589 let clockUpdate = setInterval(() => {
592 this.game.moves.length > currentMovesCount ||
593 this.game.score != "*"
595 clearInterval(clockUpdate);
598 currentTurn == "w" ? "0-1" : "1-0",
605 ppt(Math.max(0, --countdown))
609 // Post-process a (potentially partial) move (which was just played in BaseGame)
610 processMove: function(move, data) {
611 const moveCol = this.vr.turn;
612 const doProcessMove = () => {
613 const colorIdx = ["w", "b"].indexOf(moveCol);
614 const nextIdx = 1 - colorIdx;
615 if (this.game.mycolor) {
616 // NOTE: 'var' to see that variable outside this block
617 var filtered_move = getFilteredMove(move);
619 // Send move ("newmove" event) to people in the room (if our turn)
620 let addTime = data ? data.addTime : 0;
621 if (moveCol == this.game.mycolor) {
622 if (this.drawOffer == "received")
625 if (this.game.movesCount >= 2) {
626 const elapsed = Date.now() - this.game.initime[colorIdx];
627 // elapsed time is measured in milliseconds
628 addTime = this.game.increment - elapsed / 1000;
633 cancelDrawOffer: this.drawOffer == ""
635 this.send("newmove", { data: sendMove });
637 // Update current game object (no need for moves stack):
638 playMove(move, this.vr);
639 this.game.movesCount++;
640 // (add)Time indication: useful in case of lastate infos requested
641 this.game.moves.push({move:move, addTime:addTime});
642 this.game.fen = this.vr.getFen();
643 this.game.clocks[colorIdx] += addTime;
644 // data.initime is set only when I receive a "lastate" move from opponent
645 this.game.initime[nextIdx] = (data && data.initime) ? data.initime : Date.now();
647 // If repetition detected, consider that a draw offer was received:
648 const fenObj = V.ParseFen(this.game.fen);
649 let repIdx = fenObj.position + "_" + fenObj.turn;
650 if (fenObj.flags) repIdx += "_" + fenObj.flags;
651 this.repeat[repIdx] = this.repeat[repIdx] ? this.repeat[repIdx] + 1 : 1;
652 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
653 else if (this.drawOffer == "threerep") this.drawOffer = "";
654 // Since corr games are stored at only one location, update should be
655 // done only by one player for each move:
658 (this.game.type == "live" || moveCol == this.game.mycolor)
661 switch (this.drawOffer) {
666 drawCode = this.game.mycolor;
669 drawCode = V.GetOppCol(this.game.mycolor);
672 if (this.game.type == "corr") {
673 GameStorage.update(this.gameRef.id, {
676 squares: filtered_move,
678 idx: this.game.moves.length - 1
680 // Code "n" for "None" to force reset (otherwise it's ignored)
681 drawOffer: drawCode || "n"
686 GameStorage.update(this.gameRef.id, {
689 clocks: this.game.clocks,
690 initime: this.game.initime,
696 if (this.game.type == "corr" && moveCol == this.game.mycolor) {
700 this.st.tr["Move played:"] +
702 getFullNotation(move) +
704 this.st.tr["Are you sure?"]
707 this.$refs["basegame"].cancelLastMove();
711 // Let small time to finish drawing current move attempt:
714 else doProcessMove();
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.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
729 const myIdx = this.game.players.findIndex(p => {
730 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
733 // OK, I play in this game
734 GameStorage.update(this.gameRef.id, {
738 // Notify the score to main Hall. TODO: only one player (currently double send)
739 this.send("result", { gid: this.game.id, score: score });
746 <style lang="sass" scoped>
748 background-color: lightgreen
760 @media screen and (min-width: 768px)
763 @media screen and (max-width: 767px)
768 display: inline-block
771 display: inline-block
774 @media screen and (max-width: 767px)
777 @media screen and (min-width: 768px)
794 display: inline-block
798 display: inline-block
809 .draw-sent, .draw-sent:hover
810 background-color: lightyellow
812 .draw-received, .draw-received:hover
813 background-color: lightgreen
815 .draw-threerep, .draw-threerep:hover
816 background-color: #e4d1fc
819 background-color: #c5fefe