3 input#modalChat.modal(type="checkbox" @click="resetChatColor()")
4 div#chatWrap(role="dialog" data-checkbox="modalChat")
6 label.modal-close(for="modalChat")
8 span {{ Object.keys(people).length + " " + st.tr["participant(s):"] }}
9 span(v-for="p in Object.values(people)" v-if="!!p.name")
11 span.anonymous(v-if="Object.values(people).some(p => !p.name)")
13 Chat(:players="game.players" :pastChats="game.chats"
14 :newChat="newChat" @mychat="processChat")
16 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
17 span.variant-cadence {{ game.cadence }}
18 span.variant-name {{ game.vname }}
19 button#chatBtn(onClick="doClick('modalChat')") Chat
20 #actions(v-if="game.score=='*'")
21 button(@click="clickDraw()" :class="{['draw-' + drawOffer]: true}")
23 button(v-if="!!game.mycolor" @click="abortGame()") {{ st.tr["Abort"] }}
24 button(v-if="!!game.mycolor" @click="resign()") {{ st.tr["Resign"] }}
27 span.name(:class="{connected: isConnected(0)}")
28 | {{ game.players[0].name || "@nonymous" }}
29 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
31 span.name(:class="{connected: isConnected(1)}")
32 | {{ game.players[1].name || "@nonymous" }}
33 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
34 BaseGame(:game="game" :vr="vr" @newmove="processMove" @gameover="gameOver")
38 import BaseGame from "@/components/BaseGame.vue";
39 import Chat from "@/components/Chat.vue";
40 import { store } from "@/store";
41 import { GameStorage } from "@/utils/gameStorage";
42 import { ppt } from "@/utils/datetime";
43 import { extractTime } from "@/utils/timeControl";
44 import { getRandString } from "@/utils/alea";
45 import { ArrayFun } from "@/utils/array";
46 import { processModalClick } from "@/utils/modalClick";
47 import { getScoreMessage } from "@/utils/scoring";
48 import params from "@/parameters";
55 // gameRef: to find the game in (potentially remote) storage
59 gameRef: { //given in URL (rid = remote ID)
63 game: { //passed to BaseGame
64 players:[{name:""},{name:""}],
68 virtualClocks: [0, 0], //initialized with true game.clocks
69 vr: null, //"variant rules" object initialized from FEN
71 people: {}, //players + observers
72 lastate: undefined, //used if opponent send lastate before game is ready
73 repeat: {}, //detect position repetition
77 // Related to (killing of) self multi-connects:
83 "$route": function(to, from) {
84 this.gameRef.id = to.params["id"];
85 this.gameRef.rid = to.query["rid"];
89 // NOTE: some redundant code with Hall.vue (mostly related to people array)
91 // Always add myself to players' list
92 const my = this.st.user;
93 this.$set(this.people, my.sid, {id:my.id, name:my.name});
94 this.gameRef.id = this.$route.params["id"];
95 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
96 // Initialize connection
97 this.connexionString = params.socketUrl +
98 "/?sid=" + this.st.user.sid +
99 "&tmpId=" + getRandString() +
100 "&page=" + encodeURIComponent(this.$route.path);
101 this.conn = new WebSocket(this.connexionString);
102 this.conn.onmessage = this.socketMessageListener;
103 this.conn.onclose = this.socketCloseListener;
104 // Socket init required before loading remote game:
105 const socketInit = (callback) => {
106 if (!!this.conn && this.conn.readyState == 1) //1 == OPEN state
108 else //socket not ready yet (initial loading)
110 // NOTE: it's important to call callback without arguments,
111 // otherwise first arg is Websocket object and loadGame fails.
112 this.conn.onopen = () => { return callback() };
115 if (!this.gameRef.rid) //game stored locally or on server
116 this.loadGame(null, () => socketInit(this.roomInit));
117 else //game stored remotely: need socket to retrieve it
119 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
120 // --> It will be given when receiving "fullgame" socket event.
121 // A more general approach would be to store it somewhere.
122 socketInit(this.loadGame);
125 mounted: function() {
126 document.getElementById("chatWrap").addEventListener(
127 "click", processModalClick);
129 beforeDestroy: function() {
130 this.send("disconnect");
133 roomInit: function() {
134 // Notify the room only now that I connected, because
135 // messages might be lost otherwise (if game loading is slow)
136 this.send("connect");
137 this.send("pollclients");
139 send: function(code, obj) {
142 this.conn.send(JSON.stringify(
150 isConnected: function(index) {
151 const player = this.game.players[index];
153 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
155 // Try to find a match in people:
156 return Object.keys(this.people).some(sid => sid == player.sid) ||
157 Object.values(this.people).some(p => p.id == player.uid);
159 socketMessageListener: function(msg) {
162 const data = JSON.parse(msg.data);
166 data.sockIds.forEach(sid => {
167 this.$set(this.people, sid, {id:0, name:""});
168 if (sid != this.st.user.sid)
170 this.send("askidentity", {target:sid});
171 // Ask potentially missed last state, if opponent and I play
172 if (!!this.game.mycolor
173 && this.game.type == "live" && this.game.score == "*"
174 && this.game.players.some(p => p.sid == sid))
176 this.send("asklastate", {target:sid});
182 if (!this.people[data.from])
183 this.$set(this.people, data.from, {name:"", id:0});
184 if (!this.people[data.from].name)
186 this.newConnect[data.from] = true; //for self multi-connects tests
187 this.send("askidentity", {target:data.from});
191 this.$delete(this.people, data.from);
194 // I logged in elsewhere:
195 alert(this.st.tr["New connexion detected: tab now offline"]);
196 // TODO: this fails. See https://github.com/websockets/ws/issues/489
197 //this.conn.removeEventListener("message", this.socketMessageListener);
198 //this.conn.removeEventListener("close", this.socketCloseListener);
204 // Request for identification (TODO: anonymous shouldn't need to reply)
206 // Decompose to avoid revealing email
207 name: this.st.user.name,
208 sid: this.st.user.sid,
211 this.send("identity", {data:me, target:data.from});
216 const user = data.data;
217 if (!!user.name) //otherwise anonymous
219 // If I multi-connect, kill current connexion if no mark (I'm older)
220 if (this.newConnect[user.sid] && user.id > 0
221 && user.id == this.st.user.id && user.sid != this.st.user.sid)
223 if (!this.killed[this.st.user.sid])
225 this.send("killme", {sid:this.st.user.sid});
226 this.killed[this.st.user.sid] = true;
229 if (user.sid != this.st.user.sid) //I already know my identity...
231 this.$set(this.people, user.sid,
238 delete this.newConnect[user.sid];
242 // Send current (live) game if not asked by any of the players
243 if (this.game.type == "live"
244 && this.game.players.every(p => p.sid != data.from[0]))
249 players: this.game.players,
251 cadence: this.game.cadence,
252 score: this.game.score,
253 rid: this.st.user.sid, //useful in Hall if I'm an observer
255 this.send("game", {data:myGame, target:data.from});
259 this.send("fullgame", {data:this.game, target:data.from});
262 // Callback "roomInit" to poll clients only after game is loaded
263 this.loadGame(data.data, this.roomInit);
266 // Sending last state if I played a move or score != "*"
267 if ((this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
268 || this.game.score != "*" || this.drawOffer == "sent")
270 // Send our "last state" informations to opponent
271 const L = this.game.moves.length;
272 const myIdx = ["w","b"].indexOf(this.game.mycolor);
274 // NOTE: lastMove (when defined) includes addTime
275 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
276 // Since we played a move (or abort or resign),
277 // only drawOffer=="sent" is possible
278 drawSent: this.drawOffer == "sent",
279 score: this.game.score,
281 initime: this.game.initime[1-myIdx], //relevant only if I played
283 this.send("lastate", {data:myLastate, target:data.from});
286 case "lastate": //got opponent infos about last move
287 this.lastate = data.data;
288 if (this.game.rendered) //game is rendered (Board component)
289 this.processLastate();
290 //else: will be processed when game is ready
294 const move = data.data;
295 if (!!move.cancelDrawOffer) //opponent refuses draw
298 // NOTE for corr games: drawOffer reset by player in turn
299 if (this.game.type == "live" && !!this.game.mycolor)
300 GameStorage.update(this.gameRef.id, {drawOffer: ""});
302 this.$set(this.game, "moveToPlay", move);
306 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
309 this.gameOver("?", "Abort");
312 this.gameOver("1/2", data.data);
315 // NOTE: observers don't know who offered draw
316 this.drawOffer = "received";
319 this.newChat = data.data;
320 if (!document.getElementById("modalChat").checked)
321 document.getElementById("chatBtn").classList.add("somethingnew");
325 socketCloseListener: function() {
326 this.conn = new WebSocket(this.connexionString);
327 this.conn.addEventListener('message', this.socketMessageListener);
328 this.conn.addEventListener('close', this.socketCloseListener);
330 // lastate was received, but maybe game wasn't ready yet:
331 processLastate: function() {
332 const data = this.lastate;
333 this.lastate = undefined; //security...
334 const L = this.game.moves.length;
335 if (data.movesCount > L)
337 // Just got last move from him
338 this.$set(this.game, "moveToPlay", Object.assign({initime: data.initime}, data.lastMove));
341 this.drawOffer = "received";
342 if (data.score != "*")
345 if (this.game.score == "*")
346 this.gameOver(data.score);
349 clickDraw: function() {
350 if (!this.game.mycolor)
351 return; //I'm just spectator
352 if (["received","threerep"].includes(this.drawOffer))
354 if (!confirm(this.st.tr["Accept draw?"]))
356 const message = (this.drawOffer == "received"
358 : "Three repetitions");
359 this.send("draw", {data:message});
360 this.gameOver("1/2", message);
362 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
364 if (this.game.mycolor != this.vr.turn)
365 return alert(this.st.tr["Draw offer only in your turn"]);
366 if (!confirm(this.st.tr["Offer draw?"]))
368 this.drawOffer = "sent";
369 this.send("drawoffer");
370 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
373 abortGame: function() {
374 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
376 this.gameOver("?", "Abort");
379 resign: function(e) {
380 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
382 this.send("resign", {data:this.game.mycolor});
383 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
385 // 3 cases for loading a game:
386 // - from indexedDB (running or completed live game I play)
387 // - from server (one correspondance game I play[ed] or not)
388 // - from remote peer (one live game I don't play, finished or not)
389 loadGame: function(game, callback) {
390 const afterRetrieval = async (game) => {
391 const vModule = await import("@/variants/" + game.vname + ".js");
392 window.V = vModule.VariantRules;
393 this.vr = new V(game.fen);
394 const gtype = (game.cadence.indexOf('d') >= 0 ? "corr" : "live");
395 const tc = extractTime(game.cadence);
396 const myIdx = game.players.findIndex(p => {
397 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
399 const mycolor = [undefined,"w","b"][myIdx+1]; //undefined for observers
401 game.chats = []; //live games don't have chat history
404 if (game.players[0].color == "b")
406 // Adopt the same convention for live and corr games: [0] = white
407 [ game.players[0], game.players[1] ] =
408 [ game.players[1], game.players[0] ];
410 // corr game: needs to compute the clocks + initime
411 // NOTE: clocks in seconds, initime in milliseconds
412 game.clocks = [tc.mainTime, tc.mainTime];
413 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
414 if (game.score == "*") //otherwise no need to bother with time
416 game.initime = [0, 0];
417 const L = game.moves.length;
420 let addTime = [0, 0];
421 for (let i=2; i<L; i++)
423 addTime[i%2] += tc.increment -
424 (game.moves[i].played - game.moves[i-1].played) / 1000;
426 for (let i=0; i<=1; i++)
427 game.clocks[i] += addTime[i];
430 game.initime[L%2] = game.moves[L-1].played;
432 const reformattedMoves = game.moves.map( (m) => {
441 // Sort chat messages from newest to oldest
442 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
443 if (myIdx >= 0 && game.chats.length > 0)
445 // TODO: group multi-moves into an array, to deduce color from index
446 // and not need this (also repeated in BaseGame::re_setVariables())
447 let vr_tmp = new V(game.fenStart); //vr is already at end of game
448 for (let i=0; i<reformattedMoves.length; i++)
450 game.moves[i].color = vr_tmp.turn;
451 vr_tmp.play(reformattedMoves[i]);
453 // Blue background on chat button if last chat message arrived after my last move.
455 for (let midx = game.moves.length-1; midx >= 0; midx--)
457 if (game.moves[midx].color == mycolor)
459 dtLastMove = game.moves[midx].played;
463 if (dtLastMove < game.chats[0].added)
464 document.getElementById("chatBtn").classList.add("somethingnew");
466 // Now that we used idx and played, re-format moves as for live games
467 game.moves = reformattedMoves;
469 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
471 game.clocks = [tc.mainTime, tc.mainTime];
472 if (game.score == "*")
474 game.initime[0] = Date.now();
477 // I play in this live game; corr games don't have clocks+initime
478 GameStorage.update(game.id,
481 initime: game.initime,
486 if (!!game.drawOffer)
488 if (game.drawOffer == "t") //three repetitions
489 this.drawOffer = "threerep";
493 this.drawOffer = "received"; //by any of the players
496 // I play in this game:
497 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
498 this.drawOffer = "sent";
499 else //all other cases
500 this.drawOffer = "received";
505 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
506 this.game = Object.assign({},
508 // NOTE: assign mycolor here, since BaseGame could also be VS computer
511 increment: tc.increment,
513 // opponent sid not strictly required (or available), but easier
514 // at least oppsid or oppid is available anyway:
515 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
516 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
520 this.$nextTick(() => {
521 this.game.rendered = true;
522 // Did lastate arrive before game was rendered?
524 this.processLastate();
526 this.repeat = {}; //reset: scan past moves' FEN:
528 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
529 let vr_tmp = new V(game.fenStart);
530 game.moves.forEach(m => {
532 const fenObj = V.ParseFen( vr_tmp.getFen() );
533 repIdx = fenObj.position + "_" + fenObj.turn;
535 repIdx += "_" + fenObj.flags;
536 this.repeat[repIdx] = (!!this.repeat[repIdx]
537 ? this.repeat[repIdx]+1
540 if (this.repeat[repIdx] >= 3)
541 this.drawOffer = "threerep";
546 return afterRetrieval(game);
547 if (!!this.gameRef.rid)
549 // Remote live game: forgetting about callback func... (TODO: design)
550 this.send("askfullgame", {target:this.gameRef.rid});
554 // Local or corr game
555 GameStorage.get(this.gameRef.id, afterRetrieval);
558 re_setClocks: function() {
559 if (this.game.moves.length < 2 || this.game.score != "*")
561 // 1st move not completed yet, or game over: freeze time
562 this.virtualClocks = this.game.clocks.map(s => ppt(s));
565 const currentTurn = this.vr.turn;
566 const colorIdx = ["w","b"].indexOf(currentTurn);
567 let countdown = this.game.clocks[colorIdx] -
568 (Date.now() - this.game.initime[colorIdx])/1000;
569 this.virtualClocks = [0,1].map(i => {
570 const removeTime = i == colorIdx
571 ? (Date.now() - this.game.initime[colorIdx])/1000
573 return ppt(this.game.clocks[i] - removeTime);
575 let clockUpdate = setInterval(() => {
576 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
578 clearInterval(clockUpdate);
580 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
583 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
586 // Post-process a move (which was just played in BaseGame)
587 processMove: function(move) {
588 if (this.game.type == "corr" && move.color == this.game.mycolor)
590 if (!confirm(this.st.tr["Move played:"] + " " + move.notation + "\n" + this.st.tr["Are you sure?"]))
592 return this.$set(this.game, "moveToUndo", move);
595 const colorIdx = ["w","b"].indexOf(move.color);
596 const nextIdx = ["w","b"].indexOf(this.vr.turn);
597 // https://stackoverflow.com/a/38750895
598 if (!!this.game.mycolor)
600 const allowed_fields = ["appear", "vanish", "start", "end"];
601 // NOTE: 'var' to see this variable outside this block
602 var filtered_move = Object.keys(move)
603 .filter(key => allowed_fields.includes(key))
604 .reduce((obj, key) => {
605 obj[key] = move[key];
609 // Send move ("newmove" event) to people in the room (if our turn)
611 if (move.color == this.game.mycolor)
613 if (this.drawOffer == "received") //I refuse draw
615 if (this.game.moves.length >= 2) //after first move
617 const elapsed = Date.now() - this.game.initime[colorIdx];
618 // elapsed time is measured in milliseconds
619 addTime = this.game.increment - elapsed/1000;
621 const sendMove = Object.assign({},
625 cancelDrawOffer: this.drawOffer=="",
627 this.send("newmove", {data: sendMove});
628 // (Add)Time indication: useful in case of lastate infos requested
629 move.addTime = addTime;
632 addTime = move.addTime; //supposed transmitted
633 // Update current game object:
634 this.game.moves.push(move);
635 this.game.fen = move.fen;
636 this.game.clocks[colorIdx] += addTime;
637 // move.initime is set only when I receive a "lastate" move from opponent
638 this.game.initime[nextIdx] = move.initime || Date.now();
640 // If repetition detected, consider that a draw offer was received:
641 const fenObj = V.ParseFen(move.fen);
642 let repIdx = fenObj.position + "_" + fenObj.turn;
644 repIdx += "_" + fenObj.flags;
645 this.repeat[repIdx] = (!!this.repeat[repIdx]
646 ? this.repeat[repIdx]+1
648 if (this.repeat[repIdx] >= 3)
649 this.drawOffer = "threerep";
650 else if (this.drawOffer == "threerep")
652 // Since corr games are stored at only one location, update should be
653 // done only by one player for each move:
654 if (!!this.game.mycolor &&
655 (this.game.type == "live" || move.color == this.game.mycolor))
658 switch (this.drawOffer)
664 drawCode = this.game.mycolor;
667 drawCode = this.vr.turn;
670 if (this.game.type == "corr")
672 GameStorage.update(this.gameRef.id,
677 squares: filtered_move,
679 idx: this.game.moves.length - 1,
681 drawOffer: drawCode || "n", //"n" for "None" to force reset (otherwise it's ignored)
686 GameStorage.update(this.gameRef.id,
690 clocks: this.game.clocks,
691 initime: this.game.initime,
697 resetChatColor: function() {
698 // TODO: this is called twice, once on opening an once on closing
699 document.getElementById("chatBtn").classList.remove("somethingnew");
701 processChat: function(chat) {
702 this.send("newchat", {data:chat});
703 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
704 if (this.game.type == "corr" && this.st.user.id > 0)
705 GameStorage.update(this.gameRef.id, {chat: chat});
707 gameOver: function(score, scoreMsg) {
708 this.game.score = score;
709 this.game.scoreMsg = this.st.tr[(!!scoreMsg
711 : getScoreMessage(score))];
712 const myIdx = this.game.players.findIndex(p => {
713 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
715 if (myIdx >= 0) //OK, I play in this game
717 GameStorage.update(this.gameRef.id,
718 {score: score, scoreMsg: scoreMsg});
719 // Notify the score to main Hall. TODO: only one player (currently double send)
720 this.send("result", {gid:this.game.id, score:score});
727 <style lang="sass" scoped>
729 background-color: lightgreen
741 @media screen and (min-width: 768px)
744 @media screen and (max-width: 767px)
749 display: inline-block
752 display: inline-block
755 @media screen and (max-width: 767px)
758 @media screen and (min-width: 768px)
775 display: inline-block
779 display: inline-block
790 .draw-sent, .draw-sent:hover
791 background-color: lightyellow
793 .draw-received, .draw-received:hover
794 background-color: lightgreen
796 .draw-threerep, .draw-threerep:hover
797 background-color: #e4d1fc
800 background-color: #c5fefe