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";
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:""}],
67 virtualClocks: [0, 0], //initialized with true game.clocks
68 vr: null, //"variant rules" object initialized from FEN
70 people: {}, //players + observers
71 lastate: undefined, //used if opponent send lastate before game is ready
72 repeat: {}, //detect position repetition
76 tempId: "", //to distinguish several tabs
80 "$route": function(to, from) {
81 this.gameRef.id = to.params["id"];
82 this.gameRef.rid = to.query["rid"];
85 "game.clocks": function(newState) {
86 if (this.game.moves.length < 2 || this.game.score != "*")
88 // 1st move not completed yet, or game over: freeze time
89 this.virtualClocks = newState.map(s => ppt(s));
92 const currentTurn = this.vr.turn;
93 const colorIdx = ["w","b"].indexOf(currentTurn);
94 let countdown = newState[colorIdx] -
95 (Date.now() - this.game.initime[colorIdx])/1000;
96 this.virtualClocks = [0,1].map(i => {
97 const removeTime = i == colorIdx
98 ? (Date.now() - this.game.initime[colorIdx])/1000
100 return ppt(newState[i] - removeTime);
102 let clockUpdate = setInterval(() => {
103 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
105 clearInterval(clockUpdate);
107 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
110 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
114 // NOTE: some redundant code with Hall.vue (related to people array)
115 created: function() {
116 // Always add myself to players' list
117 const my = this.st.user;
118 this.$set(this.people, my.sid, {id:my.id, name:my.name});
119 this.gameRef.id = this.$route.params["id"];
120 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
121 // Initialize connection
122 this.page = this.$route.path;
123 const connexionString = params.socketUrl +
124 "/?sid=" + this.st.user.sid +
125 "&tmpId=" + this.tempId +
126 "&page=" + encodeURIComponent(this.page);
127 this.conn = new WebSocket(connexionString);
128 this.conn.onmessage = this.socketMessageListener;
129 const socketCloseListener = () => {
130 this.conn = new WebSocket(connexionString);
131 this.conn.addEventListener('message', this.socketMessageListener);
132 this.conn.addEventListener('close', socketCloseListener);
134 this.conn.onclose = socketCloseListener;
135 // Socket init required before loading remote game:
136 const socketInit = (callback) => {
137 if (!!this.conn && this.conn.readyState == 1) //1 == OPEN state
139 else //socket not ready yet (initial loading)
140 this.conn.onopen = callback;
142 if (!this.gameRef.rid) //game stored locally or on server
143 this.loadGame(null, () => socketInit(this.roomInit));
144 else //game stored remotely: need socket to retrieve it
146 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
147 // --> It will be given when receiving "fullgame" socket event.
148 // A more general approach would be to store it somewhere.
149 socketInit(this.loadGame);
152 mounted: function() {
153 document.getElementById("chatWrap").addEventListener(
154 "click", processModalClick);
156 beforeDestroy: function() {
157 this.conn.send(JSON.stringify({code:"disconnect",page:this.page}));
160 // O.1] Ask server for room composition:
161 roomInit: function() {
162 // Notify the room only now that I connected, because
163 // messages might be lost otherwise (if game loading is slow)
164 this.conn.send(JSON.stringify({code:"connect"}));
165 this.conn.send(JSON.stringify({code:"pollclients"}));
167 isConnected: function(index) {
168 const player = this.game.players[index];
170 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
172 // Try to find a match in people:
173 return Object.keys(this.people).some(sid => sid == player.sid) ||
174 Object.values(this.people).some(p => p.id == player.uid);
176 socketMessageListener: function(msg) {
177 const data = JSON.parse(msg.data);
181 this.conn.send(JSON.stringify({code:"duplicate",
182 page:"/game/" + this.game.id}));
183 alert(this.st.tr["This tab is now offline"]);
185 // 0.2] Receive clients list (just socket IDs)
187 data.sockIds.forEach(sid => {
188 if (!!this.people[sid])
190 this.$set(this.people, sid, {id:0, name:""});
192 this.conn.send(JSON.stringify({code:"askidentity", target:sid}));
196 // Request for identification: reply if I'm not anonymous
197 if (this.st.user.id > 0)
199 this.conn.send(JSON.stringify({code:"identity",
201 // NOTE: decompose to avoid revealing email
202 name: this.st.user.name,
203 sid: this.st.user.sid,
210 this.$set(this.people, data.user.sid,
211 {id: data.user.id, name: data.user.name});
212 // Ask potentially missed last state, if opponent and I play
213 if (!!this.game.mycolor
214 && this.game.type == "live" && this.game.score == "*"
215 && this.game.players.some(p => p.sid == data.user.sid))
217 this.conn.send(JSON.stringify({code:"asklastate", target:data.user.sid}));
221 // Sending last state if I played a move or score != "*"
222 if ((this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
223 || this.game.score != "*" || this.drawOffer == "sent")
225 // Send our "last state" informations to opponent
226 const L = this.game.moves.length;
227 const myIdx = ["w","b"].indexOf(this.game.mycolor);
228 this.conn.send(JSON.stringify({
233 // NOTE: lastMove (when defined) includes addTime
234 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
235 // Since we played a move (or abort or resign),
236 // only drawOffer=="sent" is possible
237 drawSent: this.drawOffer == "sent",
238 score: this.game.score,
240 initime: this.game.initime[1-myIdx], //relevant only if I played
246 // Send current (live) game if I play in (not an observer),
247 // and not asked by opponent (!)
248 if (this.game.type == "live"
249 && this.game.players.some(p => p.sid == this.st.user.sid)
250 && this.game.players.every(p => p.sid != data.from))
254 // Minimal game informations:
256 players: this.game.players,
258 timeControl: this.game.timeControl,
259 score: this.game.score,
261 this.conn.send(JSON.stringify({code:"game",
262 game:myGame, target:data.from}));
266 if (!!data.move.cancelDrawOffer) //opponent refuses draw
269 // NOTE for corr games: drawOffer reset by player in turn
270 if (this.game.type == "live" && !!this.game.mycolor)
271 GameStorage.update(this.gameRef.id, {drawOffer: ""});
273 this.$set(this.game, "moveToPlay", data.move);
276 this.newChat = data.chat;
277 if (!document.getElementById("modalChat").checked)
278 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
280 case "lastate": //got opponent infos about last move
281 this.lastate = data.state;
282 if (this.game.rendered) //game is rendered (Board component)
283 this.processLastate();
284 //else: will be processed when game is ready
287 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
290 this.gameOver("?", "Abort");
293 this.gameOver("1/2", data.message);
296 // NOTE: observers don't know who offered draw
297 this.drawOffer = "received";
300 this.conn.send(JSON.stringify({code:"fullgame",
301 game:this.game, target:data.from}));
304 // Callback "roomInit" to poll clients only after game is loaded
305 this.loadGame(data.game, this.roomInit);
308 this.$set(this.people, data.from, {name:"", id:0});
309 this.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
312 this.$delete(this.people, data.from);
316 // lastate was received, but maybe game wasn't ready yet:
317 processLastate: function() {
318 const data = this.lastate;
319 this.lastate = undefined; //security...
320 const L = this.game.moves.length;
321 if (data.movesCount > L)
323 // Just got last move from him
324 this.$set(this.game, "moveToPlay", Object.assign({}, data.lastMove, {initime: data.initime}));
327 this.drawOffer = "received";
328 if (data.score != "*")
331 if (this.game.score == "*")
332 this.gameOver(data.score);
335 clickDraw: function() {
336 if (!this.game.mycolor)
337 return; //I'm just spectator
338 if (["received","threerep"].includes(this.drawOffer))
340 if (!confirm(this.st.tr["Accept draw?"]))
342 const message = (this.drawOffer == "received"
344 : "Three repetitions");
345 Object.keys(this.people).forEach(sid => {
346 if (sid != this.st.user.sid)
348 this.conn.send(JSON.stringify({code:"draw",
349 message:message, target:sid}));
352 this.gameOver("1/2", message);
354 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
356 if (this.game.mycolor != this.vr.turn)
357 return alert(this.st.tr["Draw offer only in your turn"]);
358 if (!confirm(this.st.tr["Offer draw?"]))
360 this.drawOffer = "sent";
361 Object.keys(this.people).forEach(sid => {
362 if (sid != this.st.user.sid)
363 this.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
365 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
368 abortGame: function() {
369 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
371 this.gameOver("?", "Abort");
372 Object.keys(this.people).forEach(sid => {
373 if (sid != this.st.user.sid)
375 this.conn.send(JSON.stringify({
382 resign: function(e) {
383 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
385 Object.keys(this.people).forEach(sid => {
386 if (sid != this.st.user.sid)
388 this.conn.send(JSON.stringify({code:"resign",
389 side:this.game.mycolor, target:sid}));
392 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
394 // 3 cases for loading a game:
395 // - from indexedDB (running or completed live game I play)
396 // - from server (one correspondance game I play[ed] or not)
397 // - from remote peer (one live game I don't play, finished or not)
398 loadGame: function(game, callback) {
399 const afterRetrieval = async (game) => {
400 const vModule = await import("@/variants/" + game.vname + ".js");
401 window.V = vModule.VariantRules;
402 this.vr = new V(game.fen);
403 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
404 const tc = extractTime(game.timeControl);
407 if (game.players[0].color == "b")
409 // Adopt the same convention for live and corr games: [0] = white
410 [ game.players[0], game.players[1] ] =
411 [ game.players[1], game.players[0] ];
413 // corr game: needs to compute the clocks + initime
414 // NOTE: clocks in seconds, initime in milliseconds
415 game.clocks = [tc.mainTime, tc.mainTime];
416 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
417 if (game.score == "*") //otherwise no need to bother with time
419 game.initime = [0, 0];
420 const L = game.moves.length;
423 let addTime = [0, 0];
424 for (let i=2; i<L; i++)
426 addTime[i%2] += tc.increment -
427 (game.moves[i].played - game.moves[i-1].played) / 1000;
429 for (let i=0; i<=1; i++)
430 game.clocks[i] += addTime[i];
433 game.initime[L%2] = game.moves[L-1].played;
435 // Now that we used idx and played, re-format moves as for live games
436 game.moves = game.moves.map( (m) => {
445 // Also sort chat messages (if any)
446 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
448 const myIdx = game.players.findIndex(p => {
449 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
451 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
453 game.clocks = [tc.mainTime, tc.mainTime];
454 if (game.score == "*")
456 game.initime[0] = Date.now();
459 // I play in this live game; corr games don't have clocks+initime
460 GameStorage.update(game.id,
463 initime: game.initime,
468 if (!!game.drawOffer)
470 if (game.drawOffer == "t") //three repetitions
471 this.drawOffer = "threerep";
475 this.drawOffer = "received"; //by any of the players
478 // I play in this game:
479 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
480 this.drawOffer = "sent";
481 else //all other cases
482 this.drawOffer = "received";
487 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
488 this.game = Object.assign({},
490 // NOTE: assign mycolor here, since BaseGame could also be VS computer
493 increment: tc.increment,
494 mycolor: [undefined,"w","b"][myIdx+1],
495 // opponent sid not strictly required (or available), but easier
496 // at least oppsid or oppid is available anyway:
497 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
498 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
501 this.$nextTick(() => {
502 this.game.rendered = true;
503 // Did lastate arrive before game was rendered?
505 this.processLastate();
507 this.repeat = {}; //reset: scan past moves' FEN:
509 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
510 let vr_tmp = new V(game.fenStart);
511 game.moves.forEach(m => {
513 const fenObj = V.ParseFen( vr_tmp.getFen() );
514 repIdx = fenObj.position + "_" + fenObj.turn;
516 repIdx += "_" + fenObj.flags;
517 this.repeat[repIdx] = (!!this.repeat[repIdx]
518 ? this.repeat[repIdx]+1
521 if (this.repeat[repIdx] >= 3)
522 this.drawOffer = "threerep";
526 return afterRetrieval(game);
527 if (!!this.gameRef.rid)
529 // Remote live game: forgetting about callback func... (TODO: design)
530 this.conn.send(JSON.stringify(
531 {code:"askfullgame", target:this.gameRef.rid}));
535 // Local or corr game
536 GameStorage.get(this.gameRef.id, afterRetrieval);
539 // Post-process a move (which was just played)
540 processMove: function(move) {
541 // Update storage (corr or live) if I play in the game
542 const colorIdx = ["w","b"].indexOf(move.color);
543 const nextIdx = ["w","b"].indexOf(this.vr.turn);
544 // https://stackoverflow.com/a/38750895
545 if (!!this.game.mycolor)
547 const allowed_fields = ["appear", "vanish", "start", "end"];
548 // NOTE: 'var' to see this variable outside this block
549 var filtered_move = Object.keys(move)
550 .filter(key => allowed_fields.includes(key))
551 .reduce((obj, key) => {
552 obj[key] = move[key];
556 // Send move ("newmove" event) to people in the room (if our turn)
558 if (move.color == this.game.mycolor)
560 if (this.drawOffer == "received") //I refuse draw
562 if (this.game.moves.length >= 2) //after first move
564 const elapsed = Date.now() - this.game.initime[colorIdx];
565 // elapsed time is measured in milliseconds
566 addTime = this.game.increment - elapsed/1000;
568 const sendMove = Object.assign({},
572 cancelDrawOffer: this.drawOffer=="",
574 Object.keys(this.people).forEach(sid => {
575 if (sid != this.st.user.sid)
577 this.conn.send(JSON.stringify({
584 // (Add)Time indication: useful in case of lastate infos requested
585 move.addTime = addTime;
588 addTime = move.addTime; //supposed transmitted
589 // Update current game object:
590 this.game.moves.push(move);
591 this.game.fen = move.fen;
592 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
593 // move.initime is set only when I receive a "lastate" move from opponent
594 this.game.initime[nextIdx] = move.initime || Date.now();
595 // If repetition detected, consider that a draw offer was received:
596 const fenObj = V.ParseFen(move.fen);
597 let repIdx = fenObj.position + "_" + fenObj.turn;
599 repIdx += "_" + fenObj.flags;
600 this.repeat[repIdx] = (!!this.repeat[repIdx]
601 ? this.repeat[repIdx]+1
603 if (this.repeat[repIdx] >= 3)
604 this.drawOffer = "threerep";
605 else if (this.drawOffer == "threerep")
607 // Since corr games are stored at only one location, update should be
608 // done only by one player for each move:
609 if (!!this.game.mycolor &&
610 (this.game.type == "live" || move.color == this.game.mycolor))
613 switch (this.drawOffer)
619 drawCode = this.game.mycolor;
622 drawCode = this.vr.turn;
625 if (this.game.type == "corr")
627 GameStorage.update(this.gameRef.id,
632 squares: filtered_move,
634 idx: this.game.moves.length - 1,
636 drawOffer: drawCode || "n", //"n" for "None" to force reset (otherwise it's ignored)
641 GameStorage.update(this.gameRef.id,
645 clocks: this.game.clocks,
646 initime: this.game.initime,
652 resetChatColor: function() {
653 // TODO: this is called twice, once on opening an once on closing
654 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
656 processChat: function(chat) {
657 this.conn.send(JSON.stringify({code:"newchat", chat:chat}));
658 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
659 if (this.game.type == "corr" && this.st.user.id > 0)
660 GameStorage.update(this.gameRef.id, {chat: chat});
662 gameOver: function(score, scoreMsg) {
663 this.game.score = score;
664 this.game.scoreMsg = this.st.tr[(!!scoreMsg
666 : getScoreMessage(score))];
667 const myIdx = this.game.players.findIndex(p => {
668 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
670 if (myIdx >= 0) //OK, I play in this game
672 GameStorage.update(this.gameRef.id,
673 {score: score, scoreMsg: scoreMsg});
680 <style lang="sass" scoped>
682 background-color: lightgreen
691 @media screen and (min-width: 768px)
694 @media screen and (max-width: 767px)
699 display: inline-block
702 display: inline-block
705 @media screen and (max-width: 767px)
708 @media screen and (min-width: 768px)
722 display: inline-block
726 display: inline-block
737 .draw-sent, .draw-sent:hover
738 background-color: lightyellow
740 .draw-received, .draw-received:hover
741 background-color: lightgreen
743 .draw-threerep, .draw-threerep:hover
744 background-color: #e4d1fc