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";
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
76 "$route": function(to, from) {
77 this.gameRef.id = to.params["id"];
78 this.gameRef.rid = to.query["rid"];
81 "game.clocks": function(newState) {
82 if (this.game.moves.length < 2 || this.game.score != "*")
84 // 1st move not completed yet, or game over: freeze time
85 this.virtualClocks = newState.map(s => ppt(s));
88 const currentTurn = this.vr.turn;
89 const colorIdx = ["w","b"].indexOf(currentTurn);
90 let countdown = newState[colorIdx] -
91 (Date.now() - this.game.initime[colorIdx])/1000;
92 this.virtualClocks = [0,1].map(i => {
93 const removeTime = i == colorIdx
94 ? (Date.now() - this.game.initime[colorIdx])/1000
96 return ppt(newState[i] - removeTime);
98 let clockUpdate = setInterval(() => {
99 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
101 clearInterval(clockUpdate);
103 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
106 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
110 // NOTE: some redundant code with Hall.vue (related to people array)
111 created: function() {
112 // Always add myself to players' list
113 const my = this.st.user;
114 this.$set(this.people, my.sid, {id:my.id, name:my.name});
115 this.gameRef.id = this.$route.params["id"];
116 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
117 // Define socket .onmessage() and .onclose() events:
118 this.st.conn.onmessage = this.socketMessageListener;
119 const socketCloseListener = () => {
120 store.socketCloseListener(); //reinitialize connexion (in store.js)
121 this.st.conn.addEventListener('message', this.socketMessageListener);
122 this.st.conn.addEventListener('close', socketCloseListener);
124 this.st.conn.onclose = socketCloseListener;
125 // Socket init required before loading remote game:
126 const socketInit = (callback) => {
127 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
129 else //socket not ready yet (initial loading)
130 this.st.conn.onopen = callback;
132 if (!this.gameRef.rid) //game stored locally or on server
133 this.loadGame(null, () => socketInit(this.roomInit));
134 else //game stored remotely: need socket to retrieve it
136 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
137 // --> It will be given when receiving "fullgame" socket event.
138 // A more general approach would be to store it somewhere.
139 socketInit(this.loadGame);
142 mounted: function() {
143 document.getElementById("chatWrap").addEventListener(
144 "click", processModalClick);
147 // O.1] Ask server for room composition:
148 roomInit: function() {
149 // Notify the room only now that I connected, because
150 // messages might be lost otherwise (if game loading is slow)
151 this.st.conn.send(JSON.stringify({code:"connect"}));
152 this.st.conn.send(JSON.stringify({code:"pollclients"}));
154 isConnected: function(index) {
155 const name = this.game.players[index].name;
156 if (this.st.user.name == name)
158 return Object.values(this.people).some(p => p.name == name);
160 socketMessageListener: function(msg) {
161 const data = JSON.parse(msg.data);
165 alert(this.st.tr["Warning: multi-tabs not supported"]);
167 // 0.2] Receive clients list (just socket IDs)
170 data.sockIds.forEach(sid => {
171 if (!!this.people[sid])
173 this.$set(this.people, sid, {id:0, name:""});
175 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
181 // Request for identification: reply if I'm not anonymous
182 if (this.st.user.id > 0)
184 this.st.conn.send(JSON.stringify({code:"identity",
186 // NOTE: decompose to avoid revealing email
187 name: this.st.user.name,
188 sid: this.st.user.sid,
197 this.$set(this.people, data.user.sid,
198 {id: data.user.id, name: data.user.name});
199 // Ask potentially missed last state, if opponent and I play
200 if (!!this.game.mycolor
201 && this.game.type == "live" && this.game.score == "*"
202 && this.game.players.some(p => p.sid == data.user.sid))
204 this.st.conn.send(JSON.stringify({code:"asklastate", target:data.user.sid}));
210 // Sending last state if I played a move or score != "*"
211 if ((this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
212 || this.game.score != "*")
214 // Send our "last state" informations to opponent
215 const L = this.game.moves.length;
216 const myIdx = ["w","b"].indexOf(this.game.mycolor);
217 this.st.conn.send(JSON.stringify({
222 // NOTE: lastMove (when defined) includes addTime
223 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
224 // Since we played a move (or abort or resign),
225 // only drawOffer=="sent" is possible
226 drawSent: this.drawOffer == "sent",
227 score: this.game.score,
229 initime: this.game.initime[1-myIdx], //relevant only if I played
236 // Send current (live) game if I play in (not an observer),
237 // and not asked by opponent (!)
238 if (this.game.type == "live"
239 && this.game.players.some(p => p.sid == this.st.user.sid)
240 && this.game.players.every(p => p.sid != data.from))
244 // Minimal game informations:
246 players: this.game.players,
248 timeControl: this.game.timeControl,
250 this.st.conn.send(JSON.stringify({code:"game",
251 game:myGame, target:data.from}));
255 if (!!data.move.cancelDrawOffer) //opponent refuses draw
257 this.$set(this.game, "moveToPlay", data.move);
260 this.newChat = data.chat;
261 if (!document.getElementById("modalChat").checked)
262 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
264 case "lastate": //got opponent infos about last move
266 this.lastate = data.state;
267 if (this.game.rendered) //game is rendered (Board component)
268 this.processLastate();
269 //else: will be processed when game is ready
273 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
276 this.gameOver("?", "Abort");
279 this.gameOver("1/2", data.message);
282 // NOTE: observers don't know who offered draw
283 this.drawOffer = "received";
286 this.st.conn.send(JSON.stringify({code:"fullgame",
287 game:this.game, target:data.from}));
290 // Callback "roomInit" to poll clients only after game is loaded
291 this.loadGame(data.game, this.roomInit);
295 this.$set(this.people, data.from, {name:"", id:0});
296 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
300 this.$delete(this.people, data.from);
304 // lastate was received, but maybe game wasn't ready yet:
305 processLastate: function() {
306 const data = this.lastate;
307 this.lastate = undefined; //security...
308 const L = this.game.moves.length;
309 if (data.movesCount > L)
311 // Just got last move from him
312 const myIdx = ["w","b"].indexOf(this.game.mycolor);
314 this.drawOffer = "received";
315 this.$set(this.game, "moveToPlay", Object.assign({}, data.lastMove, {initime: data.initime}));
317 if (data.score != "*")
320 if (this.game.score == "*")
321 this.gameOver(data.score);
324 clickDraw: function() {
325 if (!this.game.mycolor)
326 return; //I'm just spectator
327 if (["received","threerep"].includes(this.drawOffer))
329 if (!confirm(this.st.tr["Accept draw?"]))
331 const message = (this.drawOffer == "received"
333 : "Three repetitions");
334 Object.keys(this.people).forEach(sid => {
335 if (sid != this.st.user.sid)
337 this.st.conn.send(JSON.stringify({code:"draw",
338 message:message, target:sid}));
341 this.gameOver("1/2", message);
343 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
345 if (this.game.mycolor != this.vr.turn)
346 return alert(this.st.tr["Draw offer only in your turn"]);
347 if (!confirm(this.st.tr["Offer draw?"]))
349 this.drawOffer = "sent";
350 Object.keys(this.people).forEach(sid => {
351 if (sid != this.st.user.sid)
352 this.st.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
354 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
357 abortGame: function() {
358 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
360 this.gameOver("?", "Abort");
361 Object.keys(this.people).forEach(sid => {
362 if (sid != this.st.user.sid)
364 this.st.conn.send(JSON.stringify({
371 resign: function(e) {
372 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
374 Object.keys(this.people).forEach(sid => {
375 if (sid != this.st.user.sid)
377 this.st.conn.send(JSON.stringify({code:"resign",
378 side:this.game.mycolor, target:sid}));
381 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
383 // 3 cases for loading a game:
384 // - from indexedDB (running or completed live game I play)
385 // - from server (one correspondance game I play[ed] or not)
386 // - from remote peer (one live game I don't play, finished or not)
387 loadGame: function(game, callback) {
388 const afterRetrieval = async (game) => {
389 const vModule = await import("@/variants/" + game.vname + ".js");
390 window.V = vModule.VariantRules;
391 this.vr = new V(game.fen);
392 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
393 const tc = extractTime(game.timeControl);
396 if (game.players[0].color == "b")
398 // Adopt the same convention for live and corr games: [0] = white
399 [ game.players[0], game.players[1] ] =
400 [ game.players[1], game.players[0] ];
402 // corr game: needs to compute the clocks + initime
403 // NOTE: clocks in seconds, initime in milliseconds
404 game.clocks = [tc.mainTime, tc.mainTime];
405 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
406 if (game.score == "*") //otherwise no need to bother with time
408 game.initime = [0, 0];
409 const L = game.moves.length;
412 let addTime = [0, 0];
413 for (let i=2; i<L; i++)
415 addTime[i%2] += tc.increment -
416 (game.moves[i].played - game.moves[i-1].played) / 1000;
418 for (let i=0; i<=1; i++)
419 game.clocks[i] += addTime[i];
422 game.initime[L%2] = game.moves[L-1].played;
424 // Now that we used idx and played, re-format moves as for live games
425 game.moves = game.moves.map( (m) => {
434 // Also sort chat messages (if any)
435 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
437 const myIdx = game.players.findIndex(p => {
438 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
440 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
442 game.clocks = [tc.mainTime, tc.mainTime];
443 if (game.score == "*")
445 game.initime[0] = Date.now();
448 // I play in this live game; corr games don't have clocks+initime
449 GameStorage.update(game.id,
452 initime: game.initime,
457 if (!!game.drawOffer)
459 if (game.drawOffer == "t") //three repetitions
460 this.drawOffer = "threerep";
464 this.drawOffer = "received"; //by any of the players
467 // I play in this game:
468 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
469 this.drawOffer = "sent";
470 else //all other cases
471 this.drawOffer = "received";
476 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
477 this.game = Object.assign({},
479 // NOTE: assign mycolor here, since BaseGame could also be VS computer
482 increment: tc.increment,
483 mycolor: [undefined,"w","b"][myIdx+1],
484 // opponent sid not strictly required (or available), but easier
485 // at least oppsid or oppid is available anyway:
486 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
487 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
490 this.$nextTick(() => {
491 this.game.rendered = true;
492 // Did lastate arrive before game was rendered?
494 this.processLastate();
496 this.repeat = {}; //reset: scan past moves' FEN:
498 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
499 let vr_tmp = new V(game.fenStart);
500 game.moves.forEach(m => {
502 const fenObj = V.ParseFen( vr_tmp.getFen() );
503 repIdx = fenObj.position + "_" + fenObj.turn;
505 repIdx += "_" + fenObj.flags;
506 this.repeat[repIdx] = (!!this.repeat[repIdx]
507 ? this.repeat[repIdx]+1
510 if (this.repeat[repIdx] >= 3)
511 this.drawOffer = "threerep";
515 return afterRetrieval(game);
516 if (!!this.gameRef.rid)
518 // Remote live game: forgetting about callback func... (TODO: design)
519 this.st.conn.send(JSON.stringify(
520 {code:"askfullgame", target:this.gameRef.rid}));
524 // Local or corr game
525 GameStorage.get(this.gameRef.id, afterRetrieval);
528 // Post-process a move (which was just played)
529 processMove: function(move) {
530 // Update storage (corr or live) if I play in the game
531 const colorIdx = ["w","b"].indexOf(move.color);
532 const nextIdx = ["w","b"].indexOf(this.vr.turn);
533 // https://stackoverflow.com/a/38750895
534 if (!!this.game.mycolor)
536 const allowed_fields = ["appear", "vanish", "start", "end"];
537 // NOTE: 'var' to see this variable outside this block
538 var filtered_move = Object.keys(move)
539 .filter(key => allowed_fields.includes(key))
540 .reduce((obj, key) => {
541 obj[key] = move[key];
545 // Send move ("newmove" event) to people in the room (if our turn)
547 if (move.color == this.game.mycolor)
549 if (this.drawOffer == "received") //I refuse draw
551 if (this.game.moves.length >= 2) //after first move
553 const elapsed = Date.now() - this.game.initime[colorIdx];
554 // elapsed time is measured in milliseconds
555 addTime = this.game.increment - elapsed/1000;
557 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
558 Object.keys(this.people).forEach(sid => {
559 if (sid != this.st.user.sid)
561 this.st.conn.send(JSON.stringify({
565 cancelDrawOffer: this.drawOffer=="",
569 // (Add)Time indication: useful in case of lastate infos requested
570 move.addTime = addTime;
573 addTime = move.addTime; //supposed transmitted
574 // Update current game object:
575 this.game.moves.push(move);
576 this.game.fen = move.fen;
577 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
578 // move.initime is set only when I receive a "lastate" move from opponent
579 this.game.initime[nextIdx] = move.initime || Date.now();
580 // If repetition detected, consider that a draw offer was received:
581 const fenObj = V.ParseFen(move.fen);
582 let repIdx = fenObj.position + "_" + fenObj.turn;
584 repIdx += "_" + fenObj.flags;
585 this.repeat[repIdx] = (!!this.repeat[repIdx]
586 ? this.repeat[repIdx]+1
588 if (this.repeat[repIdx] >= 3)
589 this.drawOffer = "threerep";
590 else if (this.drawOffer == "threerep")
592 // Since corr games are stored at only one location, update should be
593 // done only by one player for each move:
594 if (!!this.game.mycolor &&
595 (this.game.type == "live" || move.color == this.game.mycolor))
598 switch (this.drawOffer)
604 drawCode = this.game.mycolor;
607 drawCode = this.vr.turn;
610 if (this.game.type == "corr")
612 GameStorage.update(this.gameRef.id,
617 squares: filtered_move,
619 idx: this.game.moves.length - 1,
626 GameStorage.update(this.gameRef.id,
630 clocks: this.game.clocks,
631 initime: this.game.initime,
637 resetChatColor: function() {
638 // TODO: this is called twice, once on opening an once on closing
639 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
641 processChat: function(chat) {
642 this.st.conn.send(JSON.stringify({code:"newchat", chat:chat}));
643 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
644 if (this.game.type == "corr" && this.st.user.id > 0)
645 GameStorage.update(this.gameRef.id, {chat: chat});
647 gameOver: function(score, scoreMsg) {
648 this.game.score = score;
649 this.game.scoreMsg = this.st.tr[(!!scoreMsg
651 : getScoreMessage(score))];
652 const myIdx = this.game.players.findIndex(p => {
653 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
655 if (myIdx >= 0) //OK, I play in this game
657 GameStorage.update(this.gameRef.id,
658 {score: score, scoreMsg: scoreMsg});
665 <style lang="sass" scoped>
667 background-color: lightgreen
676 @media screen and (min-width: 768px)
679 @media screen and (max-width: 767px)
684 display: inline-block
687 display: inline-block
690 @media screen and (max-width: 767px)
693 @media screen and (min-width: 768px)
707 display: inline-block
711 display: inline-block
722 .draw-sent, .draw-sent:hover
723 background-color: lightyellow
725 .draw-received, .draw-received:hover
726 background-color: lightgreen
728 .draw-threerep, .draw-threerep:hover
729 background-color: #e4d1fc