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 && p.id === 0)")
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 { ajax } from "@/utils/ajax";
74 import { extractTime } from "@/utils/timeControl";
75 import { getRandString } from "@/utils/alea";
76 import { processModalClick } from "@/utils/modalClick";
77 import { getFullNotation } from "@/utils/notation";
78 import { playMove, getFilteredMove } from "@/utils/playUndo";
79 import { getScoreMessage } from "@/utils/scoring";
80 import { ArrayFun } from "@/utils/array";
81 import params from "@/parameters";
88 // gameRef: to find the game in (potentially remote) storage
93 // rid = remote (socket) ID
99 players: [{ name: "" }, { name: "" }],
103 virtualClocks: [0, 0], //initialized with true game.clocks
104 vr: null, //"variant rules" object initialized from FEN
106 people: {}, //players + observers
107 onMygames: [], //opponents (or me) on "MyGames" page
108 lastate: undefined, //used if opponent send lastate before game is ready
109 repeat: {}, //detect position repetition
113 // Related to (killing of) self multi-connects:
119 $route: function(to) {
120 this.gameRef.id = to.params["id"];
121 this.gameRef.rid = to.query["rid"];
125 // NOTE: some redundant code with Hall.vue (mostly related to people array)
126 created: function() {
127 // Always add myself to players' list
128 const my = this.st.user;
129 this.$set(this.people, my.sid, { id: my.id, name: my.name });
130 this.gameRef.id = this.$route.params["id"];
131 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
132 // Initialize connection
133 this.connexionString =
140 encodeURIComponent(this.$route.path);
141 this.conn = new WebSocket(this.connexionString);
142 this.conn.onmessage = this.socketMessageListener;
143 this.conn.onclose = this.socketCloseListener;
144 // Socket init required before loading remote game:
145 const socketInit = callback => {
146 if (!!this.conn && this.conn.readyState == 1)
150 // Socket not ready yet (initial loading)
151 // NOTE: it's important to call callback without arguments,
152 // otherwise first arg is Websocket object and loadGame fails.
153 this.conn.onopen = () => callback();
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 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)));
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:
192 Object.keys(this.people).some(sid => sid == player.sid)
197 Object.values(this.people).some(p => p.id == player.uid)
201 resetChatColor: function() {
202 // TODO: this is called twice, once on opening an once on closing
203 document.getElementById("chatBtn").classList.remove("somethingnew");
205 processChat: function(chat) {
206 this.send("newchat", { data: chat });
207 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
208 if (this.game.type == "corr" && this.st.user.id > 0)
209 GameStorage.update(this.gameRef.id, { chat: chat });
211 clearChat: function() {
212 // Nothing more to do if game is live (chats not recorded)
213 if (this.game.type == "corr") {
214 if (this.game.mycolor)
215 ajax("/chats", "DELETE", {gid: this.game.id});
216 this.game.chats = [];
219 // Notify turn after a new move (to opponent and me on MyGames page)
220 notifyTurn: function(sid) {
221 const player = this.people[sid];
222 const colorIdx = this.game.players.findIndex(
223 p => p.sid == sid || p.id == player.id);
224 const color = ["w","b"][colorIdx];
228 this.game.movesCount % 2 == 0
233 this.game.movesCount % 2 == 1
235 this.send("turnchange", { target: sid, yourTurn: yourTurn });
237 socketMessageListener: function(msg) {
238 if (!this.conn) return;
239 const data = JSON.parse(msg.data);
242 data.sockIds.forEach(sid => {
243 if (sid != this.st.user.sid) {
244 this.send("askidentity", { target: sid });
245 // Ask potentially missed last state, if opponent and I play
248 this.game.type == "live" &&
249 this.game.score == "*" &&
250 this.game.players.some(p => p.sid == sid)
252 this.send("asklastate", { target: sid });
258 if (!this.people[data.from]) {
259 this.newConnect[data.from] = true; //for self multi-connects tests
260 this.send("askidentity", { target: data.from });
264 this.$delete(this.people, data.from);
267 // TODO: from MyGames page : send mconnect message with the list of gid (live and corr)
268 // Either me (another tab) or opponent
269 const sid = data.from;
270 if (!this.onMygames.some(s => s == sid))
272 this.onMygames.push(sid);
273 this.notifyTurn(sid); //TODO: this may require server ID (so, notify after receiving identity)
276 if (!this.people[sid])
277 this.send("askidentity", { target: sid });
280 ArrayFun.remove(this.onMygames, sid => sid == data.from);
283 // I logged in elsewhere:
285 alert(this.st.tr["New connexion detected: tab now offline"]);
287 case "askidentity": {
288 // Request for identification
290 // Decompose to avoid revealing email
291 name: this.st.user.name,
292 sid: this.st.user.sid,
295 this.send("identity", { data: me, target: data.from });
299 const user = data.data;
300 this.$set(this.people, user.sid, { name: user.name, id: user.id });
302 // If I multi-connect, kill current connexion if no mark (I'm older)
304 this.newConnect[user.sid] &&
306 user.id == this.st.user.id &&
307 user.sid != this.st.user.sid
309 if (!this.killed[this.st.user.sid]) {
310 this.send("killme", { sid: this.st.user.sid });
311 this.killed[this.st.user.sid] = true;
315 delete this.newConnect[user.sid];
319 // Send current (live) game if not asked by any of the players
321 this.game.type == "live" &&
322 this.game.players.every(p => p.sid != data.from[0])
327 players: this.game.players,
329 cadence: this.game.cadence,
330 score: this.game.score,
331 rid: this.st.user.sid //useful in Hall if I'm an observer
333 this.send("game", { data: myGame, target: data.from });
337 this.send("fullgame", { data: this.game, target: data.from });
340 // Callback "roomInit" to poll clients only after game is loaded
341 let game = data.data;
342 // Move format isn't the same in storage and in browser,
343 // because of the 'addTime' field.
344 game.moves = game.moves.map(m => { return m.move || m; });
345 this.loadGame(game, this.roomInit);
348 // Sending last state if I played a move or score != "*"
350 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
351 this.game.score != "*" ||
352 this.drawOffer == "sent"
354 // Send our "last state" informations to opponent
355 const L = this.game.moves.length;
356 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
358 // NOTE: lastMove (when defined) includes addTime
359 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
360 // Since we played a move (or abort or resign),
361 // only drawOffer=="sent" is possible
362 drawSent: this.drawOffer == "sent",
363 score: this.game.score,
365 initime: this.game.initime[1 - myIdx] //relevant only if I played
367 this.send("lastate", { data: myLastate, target: data.from });
370 case "lastate": //got opponent infos about last move
371 this.lastate = data.data;
372 if (this.game.rendered)
373 // Game is rendered (Board component)
374 this.processLastate();
375 // Else: will be processed when game is ready
378 const move = data.data;
379 if (move.cancelDrawOffer) {
380 // Opponent refuses draw
382 // NOTE for corr games: drawOffer reset by player in turn
383 if (this.game.type == "live" && !!this.game.mycolor)
384 GameStorage.update(this.gameRef.id, { drawOffer: "" });
386 this.$refs["basegame"].play(
390 {addTime: move.addTime});
394 const score = data.side == "b" ? "1-0" : "0-1";
395 const side = data.side == "w" ? "White" : "Black";
396 this.gameOver(score, side + " surrender");
399 this.gameOver("?", "Stop");
402 this.gameOver("1/2", data.data);
405 // NOTE: observers don't know who offered draw
406 this.drawOffer = "received";
409 this.newChat = data.data;
410 if (!document.getElementById("modalChat").checked)
411 document.getElementById("chatBtn").classList.add("somethingnew");
415 socketCloseListener: function() {
416 this.conn = new WebSocket(this.connexionString);
417 this.conn.addEventListener("message", this.socketMessageListener);
418 this.conn.addEventListener("close", this.socketCloseListener);
420 // lastate was received, but maybe game wasn't ready yet:
421 processLastate: function() {
422 const data = this.lastate;
423 this.lastate = undefined; //security...
424 const L = this.game.moves.length;
425 if (data.movesCount > L) {
426 // Just got last move from him
427 this.$refs["basegame"].play(
431 {addTime: data.lastMove.addTime, initime: data.initime});
433 if (data.drawSent) this.drawOffer = "received";
434 if (data.score != "*") {
436 if (this.game.score == "*") this.gameOver(data.score);
439 clickDraw: function() {
440 if (!this.game.mycolor) return; //I'm just spectator
441 if (["received", "threerep"].includes(this.drawOffer)) {
442 if (!confirm(this.st.tr["Accept draw?"])) return;
444 this.drawOffer == "received"
446 : "Three repetitions";
447 this.send("draw", { data: message });
448 this.gameOver("1/2", message);
449 } else if (this.drawOffer == "") {
450 // No effect if drawOffer == "sent"
451 if (this.game.mycolor != this.vr.turn) {
452 alert(this.st.tr["Draw offer only in your turn"]);
455 if (!confirm(this.st.tr["Offer draw?"])) return;
456 this.drawOffer = "sent";
457 this.send("drawoffer");
458 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
461 abortGame: function() {
462 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
463 this.gameOver("?", "Stop");
467 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
469 this.send("resign", { data: this.game.mycolor });
470 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
471 const side = this.game.mycolor == "w" ? "White" : "Black";
472 this.gameOver(score, side + " surrender");
474 // 3 cases for loading a game:
475 // - from indexedDB (running or completed live game I play)
476 // - from server (one correspondance game I play[ed] or not)
477 // - from remote peer (one live game I don't play, finished or not)
478 loadGame: function(game, callback) {
479 const afterRetrieval = async game => {
480 const vModule = await import("@/variants/" + game.vname + ".js");
481 window.V = vModule.VariantRules;
482 this.vr = new V(game.fen);
483 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
484 const tc = extractTime(game.cadence);
485 const myIdx = game.players.findIndex(p => {
486 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
488 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
489 if (!game.chats) game.chats = []; //live games don't have chat history
490 if (gtype == "corr") {
491 if (game.players[0].color == "b") {
492 // Adopt the same convention for live and corr games: [0] = white
493 [game.players[0], game.players[1]] = [
498 // NOTE: clocks in seconds, initime in milliseconds
499 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
500 const L = game.moves.length;
501 if (game.score == "*") {
502 // Set clocks + initime
503 game.clocks = [tc.mainTime, tc.mainTime];
504 game.initime = [0, 0];
506 const gameLastupdate = game.moves[L-1].played;
507 game.initime[L % 2] = gameLastupdate;
510 tc.mainTime - (Date.now() - gameLastupdate) / 1000;
514 // Sort chat messages from newest to oldest
515 game.chats.sort((c1, c2) => {
516 return c2.added - c1.added;
518 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
519 // Did a chat message arrive after my last move?
521 if (L == 1 && myIdx == 0)
522 dtLastMove = game.moves[0].played;
525 // It's now white turn
526 dtLastMove = game.moves[L-1-(1-myIdx)].played;
529 dtLastMove = game.moves[L-1-myIdx].played;
532 if (dtLastMove < game.chats[0].added)
533 document.getElementById("chatBtn").classList.add("somethingnew");
535 // Now that we used idx and played, re-format moves as for live games
536 game.moves = game.moves.map(m => m.squares);
538 if (gtype == "live" && game.clocks[0] < 0) {
540 game.clocks = [tc.mainTime, tc.mainTime];
541 if (game.score == "*") {
542 game.initime[0] = Date.now();
544 // I play in this live game; corr games don't have clocks+initime
545 GameStorage.update(game.id, {
547 initime: game.initime
552 if (game.drawOffer) {
553 if (game.drawOffer == "t")
555 this.drawOffer = "threerep";
557 // Draw offered by any of the players:
558 if (myIdx < 0) this.drawOffer = "received";
560 // I play in this game:
562 (game.drawOffer == "w" && myIdx == 0) ||
563 (game.drawOffer == "b" && myIdx == 1)
565 this.drawOffer = "sent";
566 else this.drawOffer = "received";
570 this.repeat = {}; //reset: scan past moves' FEN:
572 let vr_tmp = new V(game.fenStart);
574 game.moves.forEach(m => {
576 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
577 this.repeat[fenIdx] = this.repeat[fenIdx]
578 ? this.repeat[fenIdx] + 1
581 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
582 this.game = Object.assign(
583 // NOTE: assign mycolor here, since BaseGame could also be VS computer
586 increment: tc.increment,
588 // opponent sid not strictly required (or available), but easier
589 // at least oppsid or oppid is available anyway:
590 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
591 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
592 movesCount: game.moves.length
597 this.$nextTick(() => {
598 this.game.rendered = true;
599 // Did lastate arrive before game was rendered?
600 if (this.lastate) this.processLastate();
602 if (callback) callback();
605 afterRetrieval(game);
608 if (this.gameRef.rid) {
609 // Remote live game: forgetting about callback func... (TODO: design)
610 this.send("askfullgame", { target: this.gameRef.rid });
612 // Local or corr game
613 // NOTE: afterRetrieval() is never called if game not found
614 GameStorage.get(this.gameRef.id, afterRetrieval);
617 re_setClocks: function() {
618 if (this.game.movesCount < 2 || this.game.score != "*") {
619 // 1st move not completed yet, or game over: freeze time
620 this.virtualClocks = this.game.clocks.map(s => ppt(s));
623 const currentTurn = this.vr.turn;
624 const currentMovesCount = this.game.moves.length;
625 const colorIdx = ["w", "b"].indexOf(currentTurn);
627 this.game.clocks[colorIdx] -
628 (Date.now() - this.game.initime[colorIdx]) / 1000;
629 this.virtualClocks = [0, 1].map(i => {
631 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
632 return ppt(this.game.clocks[i] - removeTime);
634 let clockUpdate = setInterval(() => {
637 this.game.moves.length > currentMovesCount ||
638 this.game.score != "*"
640 clearInterval(clockUpdate);
643 currentTurn == "w" ? "0-1" : "1-0",
650 ppt(Math.max(0, --countdown))
654 // Post-process a (potentially partial) move (which was just played in BaseGame)
655 // TODO?: wait for AJAX return to finish processing a move,
656 // and for opponent pingback in case of live game : if none received after e.g. 500ms, re-send newmove
657 // ...and provide move index with newmove event for basic check after receiving
658 processMove: function(move, data) {
659 const moveCol = this.vr.turn;
660 const doProcessMove = () => {
661 const colorIdx = ["w", "b"].indexOf(moveCol);
662 const nextIdx = 1 - colorIdx;
663 if (this.game.mycolor) {
664 // NOTE: 'var' to see that variable outside this block
665 var filtered_move = getFilteredMove(move);
667 // Send move ("newmove" event) to people in the room (if our turn)
668 let addTime = (data && this.game.type == "live") ? data.addTime : 0;
669 if (moveCol == this.game.mycolor) {
670 if (this.drawOffer == "received")
673 // 'addTime' is irrelevant for corr games:
674 if (this.game.type == "live" && this.game.movesCount >= 2) {
675 const elapsed = Date.now() - this.game.initime[colorIdx];
676 // elapsed time is measured in milliseconds
677 addTime = this.game.increment - elapsed / 1000;
681 addTime: addTime, //undefined for corr games
682 cancelDrawOffer: this.drawOffer == "",
683 // Players' SID required for /mygames page
684 // TODO: precompute and add this field to game object?
685 players: this.game.players.map(p => p.sid)
687 this.send("newmove", { data: sendMove });
689 // Update current game object (no need for moves stack):
690 playMove(move, this.vr);
691 this.game.movesCount++;
693 // (add)Time indication: useful in case of lastate infos requested
694 this.game.moves.push(this.game.type == "live"
695 ? {move:move, addTime:addTime}
697 this.game.fen = this.vr.getFen();
698 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
699 // In corr games, just reset clock to mainTime:
700 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
701 // data.initime is set only when I receive a "lastate" move from opponent
702 this.game.initime[nextIdx] = (data && data.initime) ? data.initime : Date.now();
704 // If repetition detected, consider that a draw offer was received:
705 const fenObj = V.ParseFen(this.game.fen);
706 let repIdx = fenObj.position + "_" + fenObj.turn;
707 if (fenObj.flags) repIdx += "_" + fenObj.flags;
708 this.repeat[repIdx] = this.repeat[repIdx] ? this.repeat[repIdx] + 1 : 1;
709 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
710 else if (this.drawOffer == "threerep") this.drawOffer = "";
711 // Since corr games are stored at only one location, update should be
712 // done only by one player for each move:
715 (this.game.type == "live" || moveCol == this.game.mycolor)
718 switch (this.drawOffer) {
723 drawCode = this.game.mycolor;
726 drawCode = V.GetOppCol(this.game.mycolor);
729 if (this.game.type == "corr") {
730 GameStorage.update(this.gameRef.id, {
733 squares: filtered_move,
735 idx: this.game.moves.length - 1
737 // Code "n" for "None" to force reset (otherwise it's ignored)
738 drawOffer: drawCode || "n"
743 GameStorage.update(this.gameRef.id, {
746 clocks: this.game.clocks,
747 initime: this.game.initime,
753 if (this.game.type == "corr" && moveCol == this.game.mycolor) {
757 this.st.tr["Move played:"] +
759 getFullNotation(move) +
761 this.st.tr["Are you sure?"]
764 this.$refs["basegame"].cancelLastMove();
768 // Let small time to finish drawing current move attempt:
771 else doProcessMove();
773 gameOver: function(score, scoreMsg) {
774 this.game.score = score;
775 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
776 const myIdx = this.game.players.findIndex(p => {
777 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
780 // OK, I play in this game
781 GameStorage.update(this.gameRef.id, {
785 // Notify the score to main Hall. TODO: only one player (currently double send)
786 this.send("result", { gid: this.game.id, score: score });
793 <style lang="sass" scoped>
795 background-color: lightgreen
807 @media screen and (min-width: 768px)
810 @media screen and (max-width: 767px)
815 display: inline-block
818 display: inline-block
821 @media screen and (max-width: 767px)
824 @media screen and (min-width: 768px)
841 display: inline-block
845 display: inline-block
856 .draw-sent, .draw-sent:hover
857 background-color: lightyellow
859 .draw-received, .draw-received:hover
860 background-color: lightgreen
862 .draw-threerep, .draw-threerep:hover
863 background-color: #e4d1fc
866 background-color: #c5fefe