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 { 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 params from "@/parameters";
87 // gameRef: to find the game in (potentially remote) storage
92 //given in URL (rid = remote ID)
98 players: [{ name: "" }, { name: "" }],
102 virtualClocks: [0, 0], //initialized with true game.clocks
103 vr: null, //"variant rules" object initialized from FEN
105 people: {}, //players + observers
106 lastate: undefined, //used if opponent send lastate before game is ready
107 repeat: {}, //detect position repetition
111 // Related to (killing of) self multi-connects:
117 $route: function(to) {
118 this.gameRef.id = to.params["id"];
119 this.gameRef.rid = to.query["rid"];
123 // NOTE: some redundant code with Hall.vue (mostly related to people array)
124 created: function() {
125 // Always add myself to players' list
126 const my = this.st.user;
127 this.$set(this.people, my.sid, { id: my.id, name: my.name });
128 this.gameRef.id = this.$route.params["id"];
129 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
130 // Initialize connection
131 this.connexionString =
138 encodeURIComponent(this.$route.path);
139 this.conn = new WebSocket(this.connexionString);
140 this.conn.onmessage = this.socketMessageListener;
141 this.conn.onclose = this.socketCloseListener;
142 // Socket init required before loading remote game:
143 const socketInit = callback => {
144 if (!!this.conn && this.conn.readyState == 1)
148 // Socket not ready yet (initial loading)
149 // NOTE: it's important to call callback without arguments,
150 // otherwise first arg is Websocket object and loadGame fails.
151 this.conn.onopen = () => {
156 if (!this.gameRef.rid)
157 // Game stored locally or on server
158 this.loadGame(null, () => socketInit(this.roomInit));
160 // Game stored remotely: need socket to retrieve it
161 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
162 // --> It will be given when receiving "fullgame" socket event.
163 // A more general approach would be to store it somewhere.
164 socketInit(this.loadGame);
167 mounted: function() {
169 .getElementById("chatWrap")
170 .addEventListener("click", processModalClick);
172 beforeDestroy: function() {
173 this.send("disconnect");
176 roomInit: function() {
177 // Notify the room only now that I connected, because
178 // messages might be lost otherwise (if game loading is slow)
179 this.send("connect");
180 this.send("pollclients");
182 send: function(code, obj) {
184 this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
187 isConnected: function(index) {
188 const player = this.game.players[index];
190 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
192 // Try to find a match in people:
194 Object.keys(this.people).some(sid => sid == player.sid) ||
195 Object.values(this.people).some(p => p.id == player.uid)
198 resetChatColor: function() {
199 // TODO: this is called twice, once on opening an once on closing
200 document.getElementById("chatBtn").classList.remove("somethingnew");
202 processChat: function(chat) {
203 this.send("newchat", { data: chat });
204 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
205 if (this.game.type == "corr" && this.st.user.id > 0)
206 GameStorage.update(this.gameRef.id, { chat: chat });
208 clearChat: function() {
209 // Nothing more to do if game is live (chats not recorded)
210 if (this.game.type == "corr") {
211 if (this.game.mycolor)
212 ajax("/chats", "DELETE", {gid: this.game.id});
213 // TODO: this.game.chats = [] could be enough here?
214 this.$set(this.game, "chats", []);
217 socketMessageListener: function(msg) {
218 if (!this.conn) return;
219 const data = JSON.parse(msg.data);
222 data.sockIds.forEach(sid => {
223 this.$set(this.people, sid, { id: 0, name: "" });
224 if (sid != this.st.user.sid) {
225 this.send("askidentity", { target: sid });
226 // Ask potentially missed last state, if opponent and I play
228 !!this.game.mycolor &&
229 this.game.type == "live" &&
230 this.game.score == "*" &&
231 this.game.players.some(p => p.sid == sid)
233 this.send("asklastate", { target: sid });
239 if (!this.people[data.from])
240 this.$set(this.people, data.from, { name: "", id: 0 });
241 if (!this.people[data.from].name) {
242 this.newConnect[data.from] = true; //for self multi-connects tests
243 this.send("askidentity", { target: data.from });
247 this.$delete(this.people, data.from);
250 // I logged in elsewhere:
251 // TODO: this fails. See https://github.com/websockets/ws/issues/489
252 //this.conn.removeEventListener("message", this.socketMessageListener);
253 //this.conn.removeEventListener("close", this.socketCloseListener);
256 alert(this.st.tr["New connexion detected: tab now offline"]);
258 case "askidentity": {
259 // Request for identification (TODO: anonymous shouldn't need to reply)
261 // Decompose to avoid revealing email
262 name: this.st.user.name,
263 sid: this.st.user.sid,
266 this.send("identity", { data: me, target: data.from });
270 const user = data.data;
272 // If I multi-connect, kill current connexion if no mark (I'm older)
274 this.newConnect[user.sid] &&
276 user.id == this.st.user.id &&
277 user.sid != this.st.user.sid
279 if (!this.killed[this.st.user.sid]) {
280 this.send("killme", { sid: this.st.user.sid });
281 this.killed[this.st.user.sid] = true;
284 if (user.sid != this.st.user.sid) {
285 //I already know my identity...
286 this.$set(this.people, user.sid, {
292 delete this.newConnect[user.sid];
296 // Send current (live) game if not asked by any of the players
298 this.game.type == "live" &&
299 this.game.players.every(p => p.sid != data.from[0])
304 players: this.game.players,
306 cadence: this.game.cadence,
307 score: this.game.score,
308 rid: this.st.user.sid //useful in Hall if I'm an observer
310 this.send("game", { data: myGame, target: data.from });
314 this.send("fullgame", { data: this.game, target: data.from });
317 // Callback "roomInit" to poll clients only after game is loaded
318 let game = data.data;
319 // Move format isn't the same in storage and in browser,
320 // because of the 'addTime' field.
321 game.moves = game.moves.map(m => { return m.move || m; });
322 this.loadGame(game, this.roomInit);
325 // Sending last state if I played a move or score != "*"
327 (this.game.moves.length > 0 && this.vr.turn != this.game.mycolor) ||
328 this.game.score != "*" ||
329 this.drawOffer == "sent"
331 // Send our "last state" informations to opponent
332 const L = this.game.moves.length;
333 const myIdx = ["w", "b"].indexOf(this.game.mycolor);
335 // NOTE: lastMove (when defined) includes addTime
336 lastMove: L > 0 ? this.game.moves[L - 1] : undefined,
337 // Since we played a move (or abort or resign),
338 // only drawOffer=="sent" is possible
339 drawSent: this.drawOffer == "sent",
340 score: this.game.score,
342 initime: this.game.initime[1 - myIdx] //relevant only if I played
344 this.send("lastate", { data: myLastate, target: data.from });
347 case "lastate": //got opponent infos about last move
348 this.lastate = data.data;
349 if (this.game.rendered)
350 // Game is rendered (Board component)
351 this.processLastate();
352 // Else: will be processed when game is ready
355 const move = data.data;
356 if (move.cancelDrawOffer) {
357 // Opponent refuses draw
359 // NOTE for corr games: drawOffer reset by player in turn
360 if (this.game.type == "live" && !!this.game.mycolor)
361 GameStorage.update(this.gameRef.id, { drawOffer: "" });
363 this.$refs["basegame"].play(
367 {addTime: move.addTime});
371 const score = data.side == "b" ? "1-0" : "0-1";
372 const side = data.side == "w" ? "White" : "Black";
373 this.gameOver(score, side + " surrender");
376 this.gameOver("?", "Stop");
379 this.gameOver("1/2", data.data);
382 // NOTE: observers don't know who offered draw
383 this.drawOffer = "received";
386 this.newChat = data.data;
387 if (!document.getElementById("modalChat").checked)
388 document.getElementById("chatBtn").classList.add("somethingnew");
392 socketCloseListener: function() {
393 this.conn = new WebSocket(this.connexionString);
394 this.conn.addEventListener("message", this.socketMessageListener);
395 this.conn.addEventListener("close", this.socketCloseListener);
397 // lastate was received, but maybe game wasn't ready yet:
398 processLastate: function() {
399 const data = this.lastate;
400 this.lastate = undefined; //security...
401 const L = this.game.moves.length;
402 if (data.movesCount > L) {
403 // Just got last move from him
404 this.$refs["basegame"].play(
408 {addTime: data.lastMove.addTime, initime: data.initime});
410 if (data.drawSent) this.drawOffer = "received";
411 if (data.score != "*") {
413 if (this.game.score == "*") this.gameOver(data.score);
416 clickDraw: function() {
417 if (!this.game.mycolor) return; //I'm just spectator
418 if (["received", "threerep"].includes(this.drawOffer)) {
419 if (!confirm(this.st.tr["Accept draw?"])) return;
421 this.drawOffer == "received"
423 : "Three repetitions";
424 this.send("draw", { data: message });
425 this.gameOver("1/2", message);
426 } else if (this.drawOffer == "") {
427 // No effect if drawOffer == "sent"
428 if (this.game.mycolor != this.vr.turn) {
429 alert(this.st.tr["Draw offer only in your turn"]);
432 if (!confirm(this.st.tr["Offer draw?"])) return;
433 this.drawOffer = "sent";
434 this.send("drawoffer");
435 GameStorage.update(this.gameRef.id, { drawOffer: this.game.mycolor });
438 abortGame: function() {
439 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"])) return;
440 this.gameOver("?", "Stop");
444 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
446 this.send("resign", { data: this.game.mycolor });
447 const score = this.game.mycolor == "w" ? "0-1" : "1-0";
448 const side = this.game.mycolor == "w" ? "White" : "Black";
449 this.gameOver(score, side + " surrender");
451 // 3 cases for loading a game:
452 // - from indexedDB (running or completed live game I play)
453 // - from server (one correspondance game I play[ed] or not)
454 // - from remote peer (one live game I don't play, finished or not)
455 loadGame: function(game, callback) {
456 const afterRetrieval = async game => {
457 const vModule = await import("@/variants/" + game.vname + ".js");
458 window.V = vModule.VariantRules;
459 this.vr = new V(game.fen);
460 const gtype = game.cadence.indexOf("d") >= 0 ? "corr" : "live";
461 const tc = extractTime(game.cadence);
462 const myIdx = game.players.findIndex(p => {
463 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
465 const mycolor = [undefined, "w", "b"][myIdx + 1]; //undefined for observers
466 if (!game.chats) game.chats = []; //live games don't have chat history
467 if (gtype == "corr") {
468 if (game.players[0].color == "b") {
469 // Adopt the same convention for live and corr games: [0] = white
470 [game.players[0], game.players[1]] = [
475 // NOTE: clocks in seconds, initime in milliseconds
476 game.moves.sort((m1, m2) => m1.idx - m2.idx); //in case of
477 const L = game.moves.length;
478 if (game.score == "*") {
479 // Set clocks + initime
480 game.clocks = [tc.mainTime, tc.mainTime];
481 game.initime = [0, 0];
483 const gameLastupdate = game.moves[L-1].played;
484 game.initime[L % 2] = gameLastupdate;
486 game.clocks[L % 2] = Date.now() - gameLastupdate;
489 // Sort chat messages from newest to oldest
490 game.chats.sort((c1, c2) => {
491 return c2.added - c1.added;
493 if (myIdx >= 0 && game.score == "*" && game.chats.length > 0) {
494 // Did a chat message arrive after my last move?
496 if (L == 1 && myIdx == 0)
497 dtLastMove = game.moves[0].played;
500 // It's now white turn
501 dtLastMove = game.moves[L-1-(1-myIdx)].played;
504 dtLastMove = game.moves[L-1-myIdx].played;
507 if (dtLastMove < game.chats[0].added)
508 document.getElementById("chatBtn").classList.add("somethingnew");
510 // Now that we used idx and played, re-format moves as for live games
511 game.moves = game.moves.map(m => m.squares);
513 if (gtype == "live" && game.clocks[0] < 0) {
515 game.clocks = [tc.mainTime, tc.mainTime];
516 if (game.score == "*") {
517 game.initime[0] = Date.now();
519 // I play in this live game; corr games don't have clocks+initime
520 GameStorage.update(game.id, {
522 initime: game.initime
527 if (game.drawOffer) {
528 if (game.drawOffer == "t")
530 this.drawOffer = "threerep";
532 // Draw offered by any of the players:
533 if (myIdx < 0) this.drawOffer = "received";
535 // I play in this game:
537 (game.drawOffer == "w" && myIdx == 0) ||
538 (game.drawOffer == "b" && myIdx == 1)
540 this.drawOffer = "sent";
541 else this.drawOffer = "received";
545 this.repeat = {}; //reset: scan past moves' FEN:
547 let vr_tmp = new V(game.fenStart);
549 game.moves.forEach(m => {
551 const fenIdx = vr_tmp.getFen().replace(/ /g, "_");
552 this.repeat[fenIdx] = this.repeat[fenIdx]
553 ? this.repeat[fenIdx] + 1
556 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
557 this.game = Object.assign(
558 // NOTE: assign mycolor here, since BaseGame could also be VS computer
561 increment: tc.increment,
563 // opponent sid not strictly required (or available), but easier
564 // at least oppsid or oppid is available anyway:
565 oppsid: myIdx < 0 ? undefined : game.players[1 - myIdx].sid,
566 oppid: myIdx < 0 ? undefined : game.players[1 - myIdx].uid,
567 movesCount: game.moves.length
572 this.$nextTick(() => {
573 this.game.rendered = true;
574 // Did lastate arrive before game was rendered?
575 if (this.lastate) this.processLastate();
577 if (callback) callback();
580 afterRetrieval(game);
583 if (this.gameRef.rid) {
584 // Remote live game: forgetting about callback func... (TODO: design)
585 this.send("askfullgame", { target: this.gameRef.rid });
587 // Local or corr game
588 // NOTE: afterRetrieval() is never called if game not found
589 GameStorage.get(this.gameRef.id, afterRetrieval);
592 re_setClocks: function() {
593 if (this.game.movesCount < 2 || this.game.score != "*") {
594 // 1st move not completed yet, or game over: freeze time
595 this.virtualClocks = this.game.clocks.map(s => ppt(s));
598 const currentTurn = this.vr.turn;
599 const currentMovesCount = this.game.moves.length;
600 const colorIdx = ["w", "b"].indexOf(currentTurn);
602 this.game.clocks[colorIdx] -
603 (Date.now() - this.game.initime[colorIdx]) / 1000;
604 this.virtualClocks = [0, 1].map(i => {
606 i == colorIdx ? (Date.now() - this.game.initime[colorIdx]) / 1000 : 0;
607 return ppt(this.game.clocks[i] - removeTime);
609 let clockUpdate = setInterval(() => {
612 this.game.moves.length > currentMovesCount ||
613 this.game.score != "*"
615 clearInterval(clockUpdate);
618 currentTurn == "w" ? "0-1" : "1-0",
625 ppt(Math.max(0, --countdown))
629 // Post-process a (potentially partial) move (which was just played in BaseGame)
630 processMove: function(move, data) {
631 const moveCol = this.vr.turn;
632 const doProcessMove = () => {
633 const colorIdx = ["w", "b"].indexOf(moveCol);
634 const nextIdx = 1 - colorIdx;
635 if (this.game.mycolor) {
636 // NOTE: 'var' to see that variable outside this block
637 var filtered_move = getFilteredMove(move);
639 // Send move ("newmove" event) to people in the room (if our turn)
640 let addTime = (data && this.game.type == "live") ? data.addTime : 0;
641 if (moveCol == this.game.mycolor) {
642 if (this.drawOffer == "received")
645 // 'addTime' is irrelevant for corr games:
646 if (this.game.type == "live" && this.game.movesCount >= 2) {
647 const elapsed = Date.now() - this.game.initime[colorIdx];
648 // elapsed time is measured in milliseconds
649 addTime = this.game.increment - elapsed / 1000;
653 addTime: addTime, //undefined for corr games
654 cancelDrawOffer: this.drawOffer == "",
655 // Players' SID required for /mygames page
656 // TODO: precompute and add this field to game object?
657 players: this.game.players.map(p => p.sid)
659 this.send("newmove", { data: sendMove });
661 // Update current game object (no need for moves stack):
662 playMove(move, this.vr);
663 this.game.movesCount++;
664 // (add)Time indication: useful in case of lastate infos requested
665 this.game.moves.push(this.game.type == "live"
666 ? {move:move, addTime:addTime}
668 this.game.fen = this.vr.getFen();
669 if (this.game.type == "live") this.game.clocks[colorIdx] += addTime;
670 // In corr games, just reset clock to mainTime:
671 else this.game.clocks[colorIdx] = extractTime(this.game.cadence).mainTime;
672 // data.initime is set only when I receive a "lastate" move from opponent
673 this.game.initime[nextIdx] = (data && data.initime) ? data.initime : Date.now();
675 // If repetition detected, consider that a draw offer was received:
676 const fenObj = V.ParseFen(this.game.fen);
677 let repIdx = fenObj.position + "_" + fenObj.turn;
678 if (fenObj.flags) repIdx += "_" + fenObj.flags;
679 this.repeat[repIdx] = this.repeat[repIdx] ? this.repeat[repIdx] + 1 : 1;
680 if (this.repeat[repIdx] >= 3) this.drawOffer = "threerep";
681 else if (this.drawOffer == "threerep") this.drawOffer = "";
682 // Since corr games are stored at only one location, update should be
683 // done only by one player for each move:
686 (this.game.type == "live" || moveCol == this.game.mycolor)
689 switch (this.drawOffer) {
694 drawCode = this.game.mycolor;
697 drawCode = V.GetOppCol(this.game.mycolor);
700 if (this.game.type == "corr") {
701 GameStorage.update(this.gameRef.id, {
704 squares: filtered_move,
706 idx: this.game.moves.length - 1
708 // Code "n" for "None" to force reset (otherwise it's ignored)
709 drawOffer: drawCode || "n"
714 GameStorage.update(this.gameRef.id, {
717 clocks: this.game.clocks,
718 initime: this.game.initime,
724 if (this.game.type == "corr" && moveCol == this.game.mycolor) {
728 this.st.tr["Move played:"] +
730 getFullNotation(move) +
732 this.st.tr["Are you sure?"]
735 this.$refs["basegame"].cancelLastMove();
739 // Let small time to finish drawing current move attempt:
742 else doProcessMove();
744 gameOver: function(score, scoreMsg) {
745 this.game.score = score;
746 this.$set(this.game, "scoreMsg", scoreMsg || getScoreMessage(score));
747 const myIdx = this.game.players.findIndex(p => {
748 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
751 // OK, I play in this game
752 GameStorage.update(this.gameRef.id, {
756 // Notify the score to main Hall. TODO: only one player (currently double send)
757 this.send("result", { gid: this.game.id, score: score });
764 <style lang="sass" scoped>
766 background-color: lightgreen
778 @media screen and (min-width: 768px)
781 @media screen and (max-width: 767px)
786 display: inline-block
789 display: inline-block
792 @media screen and (max-width: 767px)
795 @media screen and (min-width: 768px)
812 display: inline-block
816 display: inline-block
827 .draw-sent, .draw-sent:hover
828 background-color: lightyellow
830 .draw-received, .draw-received:hover
831 background-color: lightgreen
833 .draw-threerep, .draw-threerep:hover
834 background-color: #e4d1fc
837 background-color: #c5fefe