3 input#modalChat.modal(type="checkbox" @click="resetChatColor")
4 div#chatWrap(role="dialog" data-checkbox="modalChat" aria-labelledby="inputChat")
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-info {{ game.vname }}
18 button#chatBtn(onClick="doClick('modalChat')") Chat
19 #actions(v-if="game.score=='*'")
20 button(@click="clickDraw" :class="{['draw-' + drawOffer]: true}")
22 button(v-if="!!game.mycolor" @click="abortGame") {{ st.tr["Abort"] }}
23 button(v-if="!!game.mycolor" @click="resign") {{ st.tr["Resign"] }}
26 span.name(:class="{connected: isConnected(0)}")
27 | {{ game.players[0].name || "@nonymous" }}
28 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
30 span.name(:class="{connected: isConnected(1)}")
31 | {{ game.players[1].name || "@nonymous" }}
32 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
33 BaseGame(:game="game" :vr="vr" ref="basegame"
34 @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 { ArrayFun } from "@/utils/array";
45 import { processModalClick } from "@/utils/modalClick";
46 import { getScoreMessage } from "@/utils/scoring";
47 import params from "@/parameters";
54 // gameRef: to find the game in (potentially remote) storage
58 gameRef: { //given in URL (rid = remote ID)
62 game: { //passed to BaseGame
63 players:[{name:""},{name:""}],
66 virtualClocks: [0, 0], //initialized with true game.clocks
67 vr: null, //"variant rules" object initialized from FEN
69 people: {}, //players + observers
70 lastate: undefined, //used if opponent send lastate before game is ready
71 repeat: {}, //detect position repetition
77 "$route": function(to, from) {
78 this.gameRef.id = to.params["id"];
79 this.gameRef.rid = to.query["rid"];
82 "game.clocks": function(newState) {
83 if (this.game.moves.length < 2 || this.game.score != "*")
85 // 1st move not completed yet, or game over: freeze time
86 this.virtualClocks = newState.map(s => ppt(s));
89 const currentTurn = this.vr.turn;
90 const colorIdx = ["w","b"].indexOf(currentTurn);
91 let countdown = newState[colorIdx] -
92 (Date.now() - this.game.initime[colorIdx])/1000;
93 this.virtualClocks = [0,1].map(i => {
94 const removeTime = i == colorIdx
95 ? (Date.now() - this.game.initime[colorIdx])/1000
97 return ppt(newState[i] - removeTime);
99 let clockUpdate = setInterval(() => {
100 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
102 clearInterval(clockUpdate);
104 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
107 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
111 // NOTE: some redundant code with Hall.vue (mostly related to people array)
112 created: function() {
113 // Always add myself to players' list
114 const my = this.st.user;
115 this.$set(this.people, my.sid, {id:my.id, name:my.name});
116 this.gameRef.id = this.$route.params["id"];
117 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
118 // Initialize connection
119 const connexionString = params.socketUrl +
120 "/?sid=" + this.st.user.sid +
121 "&tmpId=" + getRandString() +
122 "&page=" + encodeURIComponent(this.$route.path);
123 this.conn = new WebSocket(connexionString);
124 this.conn.onmessage = this.socketMessageListener;
125 const socketCloseListener = () => {
126 this.conn = new WebSocket(connexionString);
127 this.conn.addEventListener('message', this.socketMessageListener);
128 this.conn.addEventListener('close', socketCloseListener);
130 this.conn.onclose = socketCloseListener;
131 // Socket init required before loading remote game:
132 const socketInit = (callback) => {
133 if (!!this.conn && this.conn.readyState == 1) //1 == OPEN state
135 else //socket not ready yet (initial loading)
136 this.conn.onopen = callback;
138 if (!this.gameRef.rid) //game stored locally or on server
139 this.loadGame(null, () => socketInit(this.roomInit));
140 else //game stored remotely: need socket to retrieve it
142 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
143 // --> It will be given when receiving "fullgame" socket event.
144 // A more general approach would be to store it somewhere.
145 socketInit(this.loadGame);
148 mounted: function() {
149 document.getElementById("chatWrap").addEventListener(
150 "click", processModalClick);
152 beforeDestroy: function() {
153 this.send("disconnect");
156 roomInit: function() {
157 // Notify the room only now that I connected, because
158 // messages might be lost otherwise (if game loading is slow)
159 this.send("connect");
160 this.send("pollclients");
162 send: function(code, obj) {
163 this.conn.send(JSON.stringify(
170 isConnected: function(index) {
171 const player = this.game.players[index];
173 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
175 // Try to find a match in people:
176 return Object.keys(this.people).some(sid => sid == player.sid) ||
177 Object.values(this.people).some(p => p.id == player.uid);
179 socketMessageListener: function(msg) {
180 const data = JSON.parse(msg.data);
184 data.sockIds.forEach(sid => {
185 this.$set(this.people, sid, {id:0, name:""});
186 if (sid != this.st.user.sid)
187 this.send("askidentity", {target:sid});
191 this.$set(this.people, data.from, {name:"", id:0});
192 this.send("askidentity", {target:data.from});
195 this.$delete(this.people, data.from);
198 // Request for identification: reply if I'm not anonymous
199 if (this.st.user.id > 0)
202 // NOTE: decompose to avoid revealing email
203 name: this.st.user.name,
204 sid: this.st.user.sid,
207 this.send("identity", {data:me, target:data.from});
212 const user = data.data;
213 this.$set(this.people, user.sid, {id: user.id, name: user.name});
214 // Ask potentially missed last state, if opponent and I play
215 if (!!this.game.mycolor
216 && this.game.type == "live" && this.game.score == "*"
217 && this.game.players.some(p => p.sid == user.sid))
219 this.send("asklastate", {target:user.sid});
224 // Send current (live) game if not asked by any of the players
225 if (this.game.type == "live"
226 && this.game.players.every(p => p.sid != data.from[0]))
231 players: this.game.players,
233 cadence: this.game.cadence,
234 score: this.game.score,
236 this.send("game", {data:myGame, target:data.from});
240 this.send("fullgame", {data:this.game, target:data.from});
243 // Callback "roomInit" to poll clients only after game is loaded
244 this.loadGame(data.data, this.roomInit);
247 // Sending last state if I played a move or score != "*"
248 if ((this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
249 || this.game.score != "*" || this.drawOffer == "sent")
251 // Send our "last state" informations to opponent
252 const L = this.game.moves.length;
253 const myIdx = ["w","b"].indexOf(this.game.mycolor);
255 // NOTE: lastMove (when defined) includes addTime
256 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
257 // Since we played a move (or abort or resign),
258 // only drawOffer=="sent" is possible
259 drawSent: this.drawOffer == "sent",
260 score: this.game.score,
262 initime: this.game.initime[1-myIdx], //relevant only if I played
264 this.send("lastate", {data:myLastate, target:data.from});
267 case "lastate": //got opponent infos about last move
268 this.lastate = data.data;
269 if (this.game.rendered) //game is rendered (Board component)
270 this.processLastate();
271 //else: will be processed when game is ready
275 const move = data.data;
276 if (!!move.cancelDrawOffer) //opponent refuses draw
279 // NOTE for corr games: drawOffer reset by player in turn
280 if (this.game.type == "live" && !!this.game.mycolor)
281 GameStorage.update(this.gameRef.id, {drawOffer: ""});
283 this.$set(this.game, "moveToPlay", move);
287 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
290 this.gameOver("?", "Abort");
293 this.gameOver("1/2", data.data);
296 // NOTE: observers don't know who offered draw
297 this.drawOffer = "received";
301 const chat = data.data;
303 if (!document.getElementById("modalChat").checked)
304 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
309 // lastate was received, but maybe game wasn't ready yet:
310 processLastate: function() {
311 const data = this.lastate;
312 this.lastate = undefined; //security...
313 const L = this.game.moves.length;
314 if (data.movesCount > L)
316 // Just got last move from him
317 this.$set(this.game, "moveToPlay", Object.assign({initime: data.initime}, data.lastMove));
320 this.drawOffer = "received";
321 if (data.score != "*")
324 if (this.game.score == "*")
325 this.gameOver(data.score);
328 clickDraw: function() {
329 if (!this.game.mycolor)
330 return; //I'm just spectator
331 if (["received","threerep"].includes(this.drawOffer))
333 if (!confirm(this.st.tr["Accept draw?"]))
335 const message = (this.drawOffer == "received"
337 : "Three repetitions");
338 this.send("draw", {data:message});
339 this.gameOver("1/2", message);
341 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
343 if (this.game.mycolor != this.vr.turn)
344 return alert(this.st.tr["Draw offer only in your turn"]);
345 if (!confirm(this.st.tr["Offer draw?"]))
347 this.drawOffer = "sent";
348 this.send("drawoffer");
349 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
352 abortGame: function() {
353 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
355 this.gameOver("?", "Abort");
358 resign: function(e) {
359 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
361 this.send("resign", {data:this.game.mycolor});
362 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
364 // 3 cases for loading a game:
365 // - from indexedDB (running or completed live game I play)
366 // - from server (one correspondance game I play[ed] or not)
367 // - from remote peer (one live game I don't play, finished or not)
368 loadGame: function(game, callback) {
369 const afterRetrieval = async (game) => {
370 const vModule = await import("@/variants/" + game.vname + ".js");
371 window.V = vModule.VariantRules;
372 this.vr = new V(game.fen);
373 const gtype = (game.cadence.indexOf('d') >= 0 ? "corr" : "live");
374 const tc = extractTime(game.cadence);
377 if (game.players[0].color == "b")
379 // Adopt the same convention for live and corr games: [0] = white
380 [ game.players[0], game.players[1] ] =
381 [ game.players[1], game.players[0] ];
383 // corr game: needs to compute the clocks + initime
384 // NOTE: clocks in seconds, initime in milliseconds
385 game.clocks = [tc.mainTime, tc.mainTime];
386 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
387 if (game.score == "*") //otherwise no need to bother with time
389 game.initime = [0, 0];
390 const L = game.moves.length;
393 let addTime = [0, 0];
394 for (let i=2; i<L; i++)
396 addTime[i%2] += tc.increment -
397 (game.moves[i].played - game.moves[i-1].played) / 1000;
399 for (let i=0; i<=1; i++)
400 game.clocks[i] += addTime[i];
403 game.initime[L%2] = game.moves[L-1].played;
405 // Now that we used idx and played, re-format moves as for live games
406 game.moves = game.moves.map( (m) => {
415 // Also sort chat messages (if any)
416 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
418 const myIdx = game.players.findIndex(p => {
419 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
421 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
423 game.clocks = [tc.mainTime, tc.mainTime];
424 if (game.score == "*")
426 game.initime[0] = Date.now();
429 // I play in this live game; corr games don't have clocks+initime
430 GameStorage.update(game.id,
433 initime: game.initime,
438 if (!!game.drawOffer)
440 if (game.drawOffer == "t") //three repetitions
441 this.drawOffer = "threerep";
445 this.drawOffer = "received"; //by any of the players
448 // I play in this game:
449 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
450 this.drawOffer = "sent";
451 else //all other cases
452 this.drawOffer = "received";
457 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
458 this.game = Object.assign({},
460 // NOTE: assign mycolor here, since BaseGame could also be VS computer
463 increment: tc.increment,
464 mycolor: [undefined,"w","b"][myIdx+1],
465 // opponent sid not strictly required (or available), but easier
466 // at least oppsid or oppid is available anyway:
467 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
468 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
471 this.$nextTick(() => {
472 this.game.rendered = true;
473 // Did lastate arrive before game was rendered?
475 this.processLastate();
477 this.repeat = {}; //reset: scan past moves' FEN:
479 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
480 let vr_tmp = new V(game.fenStart);
481 game.moves.forEach(m => {
483 const fenObj = V.ParseFen( vr_tmp.getFen() );
484 repIdx = fenObj.position + "_" + fenObj.turn;
486 repIdx += "_" + fenObj.flags;
487 this.repeat[repIdx] = (!!this.repeat[repIdx]
488 ? this.repeat[repIdx]+1
491 if (this.repeat[repIdx] >= 3)
492 this.drawOffer = "threerep";
496 return afterRetrieval(game);
497 if (!!this.gameRef.rid)
499 // Remote live game: forgetting about callback func... (TODO: design)
500 this.send("askfullgame", {target:this.gameRef.rid});
504 // Local or corr game
505 GameStorage.get(this.gameRef.id, afterRetrieval);
508 // Post-process a move (which was just played)
509 processMove: function(move) {
510 // Update storage (corr or live) if I play in the game
511 const colorIdx = ["w","b"].indexOf(move.color);
512 const nextIdx = ["w","b"].indexOf(this.vr.turn);
513 // https://stackoverflow.com/a/38750895
514 if (!!this.game.mycolor)
516 const allowed_fields = ["appear", "vanish", "start", "end"];
517 // NOTE: 'var' to see this variable outside this block
518 var filtered_move = Object.keys(move)
519 .filter(key => allowed_fields.includes(key))
520 .reduce((obj, key) => {
521 obj[key] = move[key];
525 // Send move ("newmove" event) to people in the room (if our turn)
527 if (move.color == this.game.mycolor)
529 if (this.drawOffer == "received") //I refuse draw
531 if (this.game.moves.length >= 2) //after first move
533 const elapsed = Date.now() - this.game.initime[colorIdx];
534 // elapsed time is measured in milliseconds
535 addTime = this.game.increment - elapsed/1000;
537 const sendMove = Object.assign({},
541 cancelDrawOffer: this.drawOffer=="",
543 this.send("newmove", {data: sendMove});
544 // (Add)Time indication: useful in case of lastate infos requested
545 move.addTime = addTime;
548 addTime = move.addTime; //supposed transmitted
549 // Update current game object:
550 this.game.moves.push(move);
551 this.game.fen = move.fen;
552 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
553 // move.initime is set only when I receive a "lastate" move from opponent
554 this.game.initime[nextIdx] = move.initime || Date.now();
555 // If repetition detected, consider that a draw offer was received:
556 const fenObj = V.ParseFen(move.fen);
557 let repIdx = fenObj.position + "_" + fenObj.turn;
559 repIdx += "_" + fenObj.flags;
560 this.repeat[repIdx] = (!!this.repeat[repIdx]
561 ? this.repeat[repIdx]+1
563 if (this.repeat[repIdx] >= 3)
564 this.drawOffer = "threerep";
565 else if (this.drawOffer == "threerep")
567 // Since corr games are stored at only one location, update should be
568 // done only by one player for each move:
569 if (!!this.game.mycolor &&
570 (this.game.type == "live" || move.color == this.game.mycolor))
573 switch (this.drawOffer)
579 drawCode = this.game.mycolor;
582 drawCode = this.vr.turn;
585 if (this.game.type == "corr")
587 GameStorage.update(this.gameRef.id,
592 squares: filtered_move,
594 idx: this.game.moves.length - 1,
596 drawOffer: drawCode || "n", //"n" for "None" to force reset (otherwise it's ignored)
601 GameStorage.update(this.gameRef.id,
605 clocks: this.game.clocks,
606 initime: this.game.initime,
612 resetChatColor: function() {
613 // TODO: this is called twice, once on opening an once on closing
614 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
616 processChat: function(chat) {
617 this.send("newchat", {data:chat});
618 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
619 if (this.game.type == "corr" && this.st.user.id > 0)
620 GameStorage.update(this.gameRef.id, {chat: chat});
622 gameOver: function(score, scoreMsg) {
623 this.game.score = score;
624 this.game.scoreMsg = this.st.tr[(!!scoreMsg
626 : getScoreMessage(score))];
627 const myIdx = this.game.players.findIndex(p => {
628 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
630 if (myIdx >= 0) //OK, I play in this game
632 GameStorage.update(this.gameRef.id,
633 {score: score, scoreMsg: scoreMsg});
640 <style lang="sass" scoped>
642 background-color: lightgreen
651 @media screen and (min-width: 768px)
654 @media screen and (max-width: 767px)
659 display: inline-block
662 display: inline-block
665 @media screen and (max-width: 767px)
668 @media screen and (min-width: 768px)
682 display: inline-block
686 display: inline-block
697 .draw-sent, .draw-sent:hover
698 background-color: lightyellow
700 .draw-received, .draw-received:hover
701 background-color: lightgreen
703 .draw-threerep, .draw-threerep:hover
704 background-color: #e4d1fc