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-sent="finishSendChat" @newchat-received="processChat")
16 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
18 | {{ st.tr["Variant:"] + " " }}
19 span.vname {{ game.vname }}
20 button#chatBtn(onClick="doClick('modalChat')") Chat
21 #actions(v-if="game.score=='*'")
22 button(@click="clickDraw" :class="{['draw-' + drawOffer]: true}")
24 button(v-if="!!game.mycolor" @click="abortGame") {{ st.tr["Abort"] }}
25 button(v-if="!!game.mycolor" @click="resign") {{ st.tr["Resign"] }}
28 span.name(:class="{connected: isConnected(0)}")
29 | {{ game.players[0].name || "@nonymous" }}
30 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
32 span.name(:class="{connected: isConnected(1)}")
33 | {{ game.players[1].name || "@nonymous" }}
34 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
35 BaseGame(:game="game" :vr="vr" ref="basegame"
36 @newmove="processMove" @gameover="gameOver")
40 import BaseGame from "@/components/BaseGame.vue";
41 import Chat from "@/components/Chat.vue";
42 import { store } from "@/store";
43 import { GameStorage } from "@/utils/gameStorage";
44 import { ppt } from "@/utils/datetime";
45 import { extractTime } from "@/utils/timeControl";
46 import { ArrayFun } from "@/utils/array";
47 import { processModalClick } from "@/utils/modalClick";
48 import { getScoreMessage } from "@/utils/scoring";
56 // gameRef: to find the game in (potentially remote) storage
60 gameRef: { //given in URL (rid = remote ID)
64 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
65 virtualClocks: [0, 0], //initialized with true game.clocks
66 vr: null, //"variant rules" object initialized from FEN
68 people: {}, //players + observers
69 lastate: undefined, //used if opponent send lastate before game is ready
70 repeat: {}, //detect position repetition
74 "$route": function(to, from) {
75 this.gameRef.id = to.params["id"];
76 this.gameRef.rid = to.query["rid"];
79 "game.clocks": function(newState) {
80 if (this.game.moves.length < 2 || this.game.score != "*")
82 // 1st move not completed yet, or game over: freeze time
83 this.virtualClocks = newState.map(s => ppt(s));
86 const currentTurn = this.vr.turn;
87 const colorIdx = ["w","b"].indexOf(currentTurn);
88 let countdown = newState[colorIdx] -
89 (Date.now() - this.game.initime[colorIdx])/1000;
90 this.virtualClocks = [0,1].map(i => {
91 const removeTime = i == colorIdx
92 ? (Date.now() - this.game.initime[colorIdx])/1000
94 return ppt(newState[i] - removeTime);
96 let clockUpdate = setInterval(() => {
97 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
99 clearInterval(clockUpdate);
101 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
104 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
108 // NOTE: some redundant code with Hall.vue (related to people array)
109 created: function() {
110 // Always add myself to players' list
111 const my = this.st.user;
112 this.$set(this.people, my.sid, {id:my.id, name:my.name});
113 this.gameRef.id = this.$route.params["id"];
114 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
115 // Define socket .onmessage() and .onclose() events:
116 this.st.conn.onmessage = this.socketMessageListener;
117 const socketCloseListener = () => {
118 store.socketCloseListener(); //reinitialize connexion (in store.js)
119 this.st.conn.addEventListener('message', this.socketMessageListener);
120 this.st.conn.addEventListener('close', socketCloseListener);
122 this.st.conn.onclose = socketCloseListener;
123 // Socket init required before loading remote game:
124 const socketInit = (callback) => {
125 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
127 else //socket not ready yet (initial loading)
128 this.st.conn.onopen = callback;
130 if (!this.gameRef.rid) //game stored locally or on server
131 this.loadGame(null, () => socketInit(this.roomInit));
132 else //game stored remotely: need socket to retrieve it
134 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
135 // --> It will be given when receiving "fullgame" socket event.
136 // A more general approach would be to store it somewhere.
137 socketInit(this.loadGame);
140 mounted: function() {
141 document.getElementById("chatWrap").addEventListener(
142 "click", processModalClick);
145 // O.1] Ask server for room composition:
146 roomInit: function() {
147 // Notify the room only now that I connected, because
148 // messages might be lost otherwise (if game loading is slow)
149 this.st.conn.send(JSON.stringify({code:"connect"}));
150 this.st.conn.send(JSON.stringify({code:"pollclients"}));
152 isConnected: function(index) {
153 const name = this.game.players[index].name;
154 if (this.st.user.name == name)
156 return Object.values(this.people).some(p => p.name == name);
158 socketMessageListener: function(msg) {
159 const data = JSON.parse(msg.data);
163 alert(this.st.tr["Warning: multi-tabs not supported"]);
165 // 0.2] Receive clients list (just socket IDs)
168 data.sockIds.forEach(sid => {
169 if (!!this.people[sid])
171 this.$set(this.people, sid, {id:0, name:""});
173 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
179 // Request for identification: reply if I'm not anonymous
180 if (this.st.user.id > 0)
182 this.st.conn.send(JSON.stringify({code:"identity",
184 // NOTE: decompose to avoid revealing email
185 name: this.st.user.name,
186 sid: this.st.user.sid,
195 // NOTE: sometimes player.id fails because player is undefined...
196 // Probably because the event was meant for Hall?
197 if (!this.people[data.user.sid])
199 this.$set(this.people, data.user.sid,
200 {id: data.user.id, name: data.user.name});
201 // Sending last state only for live games: corr games are complete,
202 // only if I played a move (otherwise opponent has all)
203 if (!!this.game.mycolor && this.game.type == "live"
204 && this.game.oppsid == data.user.sid
205 && this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
207 // Send our "last state" informations to opponent
208 const L = this.game.moves.length;
209 this.st.conn.send(JSON.stringify({
211 target: data.user.sid,
214 lastMove: this.game.moves[L-1],
215 // Since we played a move, only drawOffer=="sent" is possible
216 drawSent: this.drawOffer == "sent",
217 score: this.game.score,
219 clocks: this.game.clocks,
226 // Send current (live) game if I play in (not an observer),
227 // and not asked by opponent (!)
228 if (this.game.type == "live"
229 && this.game.players.some(p => p.sid == this.st.user.sid)
230 && this.game.players.every(p => p.sid != data.from))
234 // Minimal game informations:
236 players: this.game.players,
238 timeControl: this.game.timeControl,
240 this.st.conn.send(JSON.stringify({code:"game",
241 game:myGame, target:data.from}));
245 if (!!data.move.cancelDrawOffer) //opponent refuses draw
247 this.$set(this.game, "moveToPlay", data.move);
249 case "lastate": //got opponent infos about last move
252 if (!!this.game.type) //game is loaded
253 this.processLastate();
254 //else: will be processed when game is ready
258 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
261 this.gameOver("?", "Abort");
264 this.gameOver("1/2", data.message);
267 // NOTE: observers don't know who offered draw
268 this.drawOffer = "received";
271 this.st.conn.send(JSON.stringify({code:"fullgame",
272 game:this.game, target:data.from}));
275 // Callback "roomInit" to poll clients only after game is loaded
276 this.loadGame(data.game, this.roomInit);
280 // TODO: next condition is probably not required. See note line 150
281 if (!this.people[data.from])
283 this.$set(this.people, data.from, {name:"", id:0});
284 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
289 this.$delete(this.people, data.from);
293 // lastate was received, but maybe game wasn't ready yet:
294 processLastate: function() {
295 const data = this.lastate;
296 this.lastate = undefined; //security...
297 const L = this.game.moves.length;
298 if (data.movesCount > L)
300 // Just got last move from him
301 if (data.score != "*" && this.game.score == "*")
302 this.gameOver(data.score);
303 this.game.clocks = data.clocks; //TODO: check this?
305 this.drawOffer = "received";
306 this.$set(this.game, "moveToPlay", data.lastMove);
309 clickDraw: function() {
310 if (!this.game.mycolor)
311 return; //I'm just spectator
312 if (["received","threerep"].includes(this.drawOffer))
314 if (!confirm(this.st.tr["Accept draw?"]))
316 const message = (this.drawOffer == "received"
318 : "Three repetitions");
319 Object.keys(this.people).forEach(sid => {
320 if (sid != this.st.user.sid)
322 this.st.conn.send(JSON.stringify({code:"draw",
323 message:message, target:sid}));
326 this.gameOver("1/2", message);
328 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
330 if (this.game.mycolor != this.vr.turn)
331 return alert(this.st.tr["Draw offer only in your turn"]);
332 if (!confirm(this.st.tr["Offer draw?"]))
334 this.drawOffer = "sent";
335 Object.keys(this.people).forEach(sid => {
336 if (sid != this.st.user.sid)
337 this.st.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
339 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
342 abortGame: function() {
343 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
345 this.gameOver("?", "Abort");
346 Object.keys(this.people).forEach(sid => {
347 if (sid != this.st.user.sid)
349 this.st.conn.send(JSON.stringify({
356 resign: function(e) {
357 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
359 Object.keys(this.people).forEach(sid => {
360 if (sid != this.st.user.sid)
362 this.st.conn.send(JSON.stringify({code:"resign",
363 side:this.game.mycolor, target:sid}));
366 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
368 // 3 cases for loading a game:
369 // - from indexedDB (running or completed live game I play)
370 // - from server (one correspondance game I play[ed] or not)
371 // - from remote peer (one live game I don't play, finished or not)
372 loadGame: function(game, callback) {
373 const afterRetrieval = async (game) => {
374 const vModule = await import("@/variants/" + game.vname + ".js");
375 window.V = vModule.VariantRules;
376 this.vr = new V(game.fen);
377 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
378 const tc = extractTime(game.timeControl);
381 if (game.players[0].color == "b")
383 // Adopt the same convention for live and corr games: [0] = white
384 [ game.players[0], game.players[1] ] =
385 [ game.players[1], game.players[0] ];
387 // corr game: needs to compute the clocks + initime
388 // NOTE: clocks in seconds, initime in milliseconds
389 game.clocks = [tc.mainTime, tc.mainTime];
390 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
391 if (game.score == "*") //otherwise no need to bother with time
393 game.initime = [0, 0];
394 const L = game.moves.length;
397 let addTime = [0, 0];
398 for (let i=2; i<L; i++)
400 addTime[i%2] += tc.increment -
401 (game.moves[i].played - game.moves[i-1].played) / 1000;
403 for (let i=0; i<=1; i++)
404 game.clocks[i] += addTime[i];
407 game.initime[L%2] = game.moves[L-1].played;
409 // Now that we used idx and played, re-format moves as for live games
410 game.moves = game.moves.map( (m) => {
419 // Also sort chat messages (if any)
420 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
422 const myIdx = game.players.findIndex(p => {
423 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
425 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
427 game.clocks = [tc.mainTime, tc.mainTime];
428 if (game.score == "*")
430 game.initime[0] = Date.now();
433 // I play in this live game; corr games don't have clocks+initime
434 GameStorage.update(game.id,
437 initime: game.initime,
442 if (!!game.drawOffer)
444 if (game.drawOffer == "t") //three repetitions
445 this.drawOffer = "threerep";
449 this.drawOffer = "received"; //by any of the players
452 // I play in this game:
453 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
454 this.drawOffer = "sent";
455 else //all other cases
456 this.drawOffer = "received";
461 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
462 this.game = Object.assign({},
464 // NOTE: assign mycolor here, since BaseGame could also be VS computer
467 increment: tc.increment,
468 mycolor: [undefined,"w","b"][myIdx+1],
469 // opponent sid not strictly required (or available), but easier
470 // at least oppsid or oppid is available anyway:
471 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
472 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
475 this.repeat = {}; //reset: scan past moves' FEN:
477 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
478 let vr_tmp = new V(game.fenStart);
479 game.moves.forEach(m => {
481 const fenObj = V.ParseFen( vr_tmp.getFen() );
482 repIdx = fenObj.position + "_" + fenObj.turn;
484 repIdx += "_" + fenObj.flags;
485 this.repeat[repIdx] = (!!this.repeat[repIdx]
486 ? this.repeat[repIdx]+1
489 if (this.repeat[repIdx] >= 3)
490 this.drawOffer = "threerep";
491 if (!!this.lastate) //lastate arrived before game was loaded:
492 this.processLastate();
496 return afterRetrieval(game);
497 if (!!this.gameRef.rid)
499 // Remote live game: forgetting about callback func... (TODO: design)
500 this.st.conn.send(JSON.stringify(
501 {code:"askfullgame", target:this.gameRef.rid}));
505 // Local or corr game
506 GameStorage.get(this.gameRef.id, afterRetrieval);
509 // Post-process a move (which was just played)
510 processMove: function(move) {
511 // Update storage (corr or live) if I play in the game
512 const colorIdx = ["w","b"].indexOf(move.color);
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 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
538 Object.keys(this.people).forEach(sid => {
539 if (sid != this.st.user.sid)
541 this.st.conn.send(JSON.stringify({
545 cancelDrawOffer: this.drawOffer=="",
551 addTime = move.addTime; //supposed transmitted
552 const nextIdx = ["w","b"].indexOf(this.vr.turn);
553 // Update current game object:
554 this.game.moves.push(move);
555 this.game.fen = move.fen;
556 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
557 this.game.initime[nextIdx] = Date.now();
558 // If repetition detected, consider that a draw offer was received:
559 const fenObj = V.ParseFen(move.fen);
560 let repIdx = fenObj.position + "_" + fenObj.turn;
562 repIdx += "_" + fenObj.flags;
563 this.repeat[repIdx] = (!!this.repeat[repIdx]
564 ? this.repeat[repIdx]+1
566 if (this.repeat[repIdx] >= 3)
567 this.drawOffer = "threerep";
568 else if (this.drawOffer == "threerep")
570 // Since corr games are stored at only one location, update should be
571 // done only by one player for each move:
572 if (!!this.game.mycolor &&
573 (this.game.type == "live" || move.color == this.game.mycolor))
576 switch (this.drawOffer)
582 drawCode = this.game.mycolor;
585 drawCode = this.vr.turn;
588 if (this.game.type == "corr")
590 GameStorage.update(this.gameRef.id,
595 squares: filtered_move,
596 played: Date.now(), //TODO: on server?
597 idx: this.game.moves.length - 1,
604 GameStorage.update(this.gameRef.id,
608 clocks: this.game.clocks,
609 initime: this.game.initime,
615 resetChatColor: function() {
616 // TODO: this is called twice, once on opening an once on closing
617 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
619 finishSendChat: function(chat) {
620 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
621 if (this.game.type == "corr" && this.st.user.id > 0)
622 GameStorage.update(this.gameRef.id, {chat: chat});
624 processChat: function() {
625 if (!document.getElementById("modalChat").checked)
626 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
628 gameOver: function(score, scoreMsg) {
629 this.game.score = score;
630 this.game.scoreMsg = this.st.tr[(!!scoreMsg
632 : getScoreMessage(score))];
633 const myIdx = this.game.players.findIndex(p => {
634 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
636 if (myIdx >= 0) //OK, I play in this game
638 GameStorage.update(this.gameRef.id,
639 {score: score, scoreMsg: scoreMsg});
646 <style lang="sass" scoped>
648 background-color: lightgreen
657 @media screen and (min-width: 768px)
660 @media screen and (max-width: 767px)
665 display: inline-block
668 display: inline-block
672 @media screen and (max-width: 767px)
675 @media screen and (min-width: 768px)
690 display: inline-block
694 display: inline-block
705 .draw-sent, .draw-sent:hover
706 background-color: lightyellow
708 .draw-received, .draw-received:hover
709 background-color: lightgreen
711 .draw-threerep, .draw-threerep:hover
712 background-color: #e4d1fc