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: {players:[{name:""},{name:""}]}, //passed to BaseGame
63 virtualClocks: [0, 0], //initialized with true game.clocks
64 vr: null, //"variant rules" object initialized from FEN
66 people: {}, //players + observers
67 lastate: undefined, //used if opponent send lastate before game is ready
68 repeat: {}, //detect position repetition
73 "$route": function(to, from) {
74 this.gameRef.id = to.params["id"];
75 this.gameRef.rid = to.query["rid"];
78 "game.clocks": function(newState) {
79 if (this.game.moves.length < 2 || this.game.score != "*")
81 // 1st move not completed yet, or game over: freeze time
82 this.virtualClocks = newState.map(s => ppt(s));
85 const currentTurn = this.vr.turn;
86 const colorIdx = ["w","b"].indexOf(currentTurn);
87 let countdown = newState[colorIdx] -
88 (Date.now() - this.game.initime[colorIdx])/1000;
89 this.virtualClocks = [0,1].map(i => {
90 const removeTime = i == colorIdx
91 ? (Date.now() - this.game.initime[colorIdx])/1000
93 return ppt(newState[i] - removeTime);
95 let clockUpdate = setInterval(() => {
96 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
98 clearInterval(clockUpdate);
100 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
103 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
107 // NOTE: some redundant code with Hall.vue (related to people array)
108 created: function() {
109 // Always add myself to players' list
110 const my = this.st.user;
111 this.$set(this.people, my.sid, {id:my.id, name:my.name});
112 this.gameRef.id = this.$route.params["id"];
113 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
114 // Define socket .onmessage() and .onclose() events:
115 this.st.conn.onmessage = this.socketMessageListener;
116 const socketCloseListener = () => {
117 store.socketCloseListener(); //reinitialize connexion (in store.js)
118 this.st.conn.addEventListener('message', this.socketMessageListener);
119 this.st.conn.addEventListener('close', socketCloseListener);
121 this.st.conn.onclose = socketCloseListener;
122 // Socket init required before loading remote game:
123 const socketInit = (callback) => {
124 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
126 else //socket not ready yet (initial loading)
127 this.st.conn.onopen = callback;
129 if (!this.gameRef.rid) //game stored locally or on server
130 this.loadGame(null, () => socketInit(this.roomInit));
131 else //game stored remotely: need socket to retrieve it
133 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
134 // --> It will be given when receiving "fullgame" socket event.
135 // A more general approach would be to store it somewhere.
136 socketInit(this.loadGame);
139 mounted: function() {
140 document.getElementById("chatWrap").addEventListener(
141 "click", processModalClick);
144 // O.1] Ask server for room composition:
145 roomInit: function() {
146 // Notify the room only now that I connected, because
147 // messages might be lost otherwise (if game loading is slow)
148 this.st.conn.send(JSON.stringify({code:"connect"}));
149 this.st.conn.send(JSON.stringify({code:"pollclients"}));
151 isConnected: function(index) {
152 const name = this.game.players[index].name;
153 if (this.st.user.name == name)
155 return Object.values(this.people).some(p => p.name == name);
157 socketMessageListener: function(msg) {
158 const data = JSON.parse(msg.data);
162 alert(this.st.tr["Warning: multi-tabs not supported"]);
164 // 0.2] Receive clients list (just socket IDs)
167 data.sockIds.forEach(sid => {
168 if (!!this.people[sid])
170 this.$set(this.people, sid, {id:0, name:""});
172 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
178 // Request for identification: reply if I'm not anonymous
179 if (this.st.user.id > 0)
181 this.st.conn.send(JSON.stringify({code:"identity",
183 // NOTE: decompose to avoid revealing email
184 name: this.st.user.name,
185 sid: this.st.user.sid,
194 // NOTE: sometimes player.id fails because player is undefined...
195 // Probably because the event was meant for Hall?
196 if (!this.people[data.user.sid])
198 this.$set(this.people, data.user.sid,
199 {id: data.user.id, name: data.user.name});
200 // Sending last state only for live games: corr games are complete,
201 // only if I played a move (otherwise opponent has all)
202 if (!!this.game.mycolor && this.game.type == "live"
203 && this.game.oppsid == data.user.sid
204 && this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
206 // Send our "last state" informations to opponent
207 const L = this.game.moves.length;
208 this.st.conn.send(JSON.stringify({
210 target: data.user.sid,
213 lastMove: this.game.moves[L-1],
214 // Since we played a move, only drawOffer=="sent" is possible
215 drawSent: this.drawOffer == "sent",
216 score: this.game.score,
218 clocks: this.game.clocks,
225 // Send current (live) game if I play in (not an observer),
226 // and not asked by opponent (!)
227 if (this.game.type == "live"
228 && this.game.players.some(p => p.sid == this.st.user.sid)
229 && this.game.players.every(p => p.sid != data.from))
233 // Minimal game informations:
235 players: this.game.players,
237 timeControl: this.game.timeControl,
239 this.st.conn.send(JSON.stringify({code:"game",
240 game:myGame, target:data.from}));
244 if (!!data.move.cancelDrawOffer) //opponent refuses draw
246 this.$set(this.game, "moveToPlay", data.move);
249 this.newChat = data.chat;
250 if (!document.getElementById("modalChat").checked)
251 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
253 case "lastate": //got opponent infos about last move
256 if (!!this.game.type) //game is loaded
257 this.processLastate();
258 //else: will be processed when game is ready
262 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
265 this.gameOver("?", "Abort");
268 this.gameOver("1/2", data.message);
271 // NOTE: observers don't know who offered draw
272 this.drawOffer = "received";
275 this.st.conn.send(JSON.stringify({code:"fullgame",
276 game:this.game, target:data.from}));
279 // Callback "roomInit" to poll clients only after game is loaded
280 this.loadGame(data.game, this.roomInit);
284 // TODO: next condition is probably not required. See note line 150
285 if (!this.people[data.from])
287 this.$set(this.people, data.from, {name:"", id:0});
288 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
293 this.$delete(this.people, data.from);
297 // lastate was received, but maybe game wasn't ready yet:
298 processLastate: function() {
299 const data = this.lastate;
300 this.lastate = undefined; //security...
301 const L = this.game.moves.length;
302 if (data.movesCount > L)
304 // Just got last move from him
305 if (data.score != "*" && this.game.score == "*")
306 this.gameOver(data.score);
307 this.game.clocks = data.clocks; //TODO: check this?
309 this.drawOffer = "received";
310 this.$set(this.game, "moveToPlay", data.lastMove);
313 clickDraw: function() {
314 if (!this.game.mycolor)
315 return; //I'm just spectator
316 if (["received","threerep"].includes(this.drawOffer))
318 if (!confirm(this.st.tr["Accept draw?"]))
320 const message = (this.drawOffer == "received"
322 : "Three repetitions");
323 Object.keys(this.people).forEach(sid => {
324 if (sid != this.st.user.sid)
326 this.st.conn.send(JSON.stringify({code:"draw",
327 message:message, target:sid}));
330 this.gameOver("1/2", message);
332 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
334 if (this.game.mycolor != this.vr.turn)
335 return alert(this.st.tr["Draw offer only in your turn"]);
336 if (!confirm(this.st.tr["Offer draw?"]))
338 this.drawOffer = "sent";
339 Object.keys(this.people).forEach(sid => {
340 if (sid != this.st.user.sid)
341 this.st.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
343 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
346 abortGame: function() {
347 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
349 this.gameOver("?", "Abort");
350 Object.keys(this.people).forEach(sid => {
351 if (sid != this.st.user.sid)
353 this.st.conn.send(JSON.stringify({
360 resign: function(e) {
361 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
363 Object.keys(this.people).forEach(sid => {
364 if (sid != this.st.user.sid)
366 this.st.conn.send(JSON.stringify({code:"resign",
367 side:this.game.mycolor, target:sid}));
370 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
372 // 3 cases for loading a game:
373 // - from indexedDB (running or completed live game I play)
374 // - from server (one correspondance game I play[ed] or not)
375 // - from remote peer (one live game I don't play, finished or not)
376 loadGame: function(game, callback) {
377 const afterRetrieval = async (game) => {
378 const vModule = await import("@/variants/" + game.vname + ".js");
379 window.V = vModule.VariantRules;
380 this.vr = new V(game.fen);
381 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
382 const tc = extractTime(game.timeControl);
385 if (game.players[0].color == "b")
387 // Adopt the same convention for live and corr games: [0] = white
388 [ game.players[0], game.players[1] ] =
389 [ game.players[1], game.players[0] ];
391 // corr game: needs to compute the clocks + initime
392 // NOTE: clocks in seconds, initime in milliseconds
393 game.clocks = [tc.mainTime, tc.mainTime];
394 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
395 if (game.score == "*") //otherwise no need to bother with time
397 game.initime = [0, 0];
398 const L = game.moves.length;
401 let addTime = [0, 0];
402 for (let i=2; i<L; i++)
404 addTime[i%2] += tc.increment -
405 (game.moves[i].played - game.moves[i-1].played) / 1000;
407 for (let i=0; i<=1; i++)
408 game.clocks[i] += addTime[i];
411 game.initime[L%2] = game.moves[L-1].played;
413 // Now that we used idx and played, re-format moves as for live games
414 game.moves = game.moves.map( (m) => {
423 // Also sort chat messages (if any)
424 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
426 const myIdx = game.players.findIndex(p => {
427 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
429 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
431 game.clocks = [tc.mainTime, tc.mainTime];
432 if (game.score == "*")
434 game.initime[0] = Date.now();
437 // I play in this live game; corr games don't have clocks+initime
438 GameStorage.update(game.id,
441 initime: game.initime,
446 if (!!game.drawOffer)
448 if (game.drawOffer == "t") //three repetitions
449 this.drawOffer = "threerep";
453 this.drawOffer = "received"; //by any of the players
456 // I play in this game:
457 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
458 this.drawOffer = "sent";
459 else //all other cases
460 this.drawOffer = "received";
465 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
466 this.game = Object.assign({},
468 // NOTE: assign mycolor here, since BaseGame could also be VS computer
471 increment: tc.increment,
472 mycolor: [undefined,"w","b"][myIdx+1],
473 // opponent sid not strictly required (or available), but easier
474 // at least oppsid or oppid is available anyway:
475 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
476 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
479 this.repeat = {}; //reset: scan past moves' FEN:
481 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
482 let vr_tmp = new V(game.fenStart);
483 game.moves.forEach(m => {
485 const fenObj = V.ParseFen( vr_tmp.getFen() );
486 repIdx = fenObj.position + "_" + fenObj.turn;
488 repIdx += "_" + fenObj.flags;
489 this.repeat[repIdx] = (!!this.repeat[repIdx]
490 ? this.repeat[repIdx]+1
493 if (this.repeat[repIdx] >= 3)
494 this.drawOffer = "threerep";
495 if (!!this.lastate) //lastate arrived before game was loaded:
496 this.processLastate();
500 return afterRetrieval(game);
501 if (!!this.gameRef.rid)
503 // Remote live game: forgetting about callback func... (TODO: design)
504 this.st.conn.send(JSON.stringify(
505 {code:"askfullgame", target:this.gameRef.rid}));
509 // Local or corr game
510 GameStorage.get(this.gameRef.id, afterRetrieval);
513 // Post-process a move (which was just played)
514 processMove: function(move) {
515 // Update storage (corr or live) if I play in the game
516 const colorIdx = ["w","b"].indexOf(move.color);
517 // https://stackoverflow.com/a/38750895
518 if (!!this.game.mycolor)
520 const allowed_fields = ["appear", "vanish", "start", "end"];
521 // NOTE: 'var' to see this variable outside this block
522 var filtered_move = Object.keys(move)
523 .filter(key => allowed_fields.includes(key))
524 .reduce((obj, key) => {
525 obj[key] = move[key];
529 // Send move ("newmove" event) to people in the room (if our turn)
531 if (move.color == this.game.mycolor)
533 if (this.drawOffer == "received") //I refuse draw
535 if (this.game.moves.length >= 2) //after first move
537 const elapsed = Date.now() - this.game.initime[colorIdx];
538 // elapsed time is measured in milliseconds
539 addTime = this.game.increment - elapsed/1000;
541 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
542 Object.keys(this.people).forEach(sid => {
543 if (sid != this.st.user.sid)
545 this.st.conn.send(JSON.stringify({
549 cancelDrawOffer: this.drawOffer=="",
555 addTime = move.addTime; //supposed transmitted
556 const nextIdx = ["w","b"].indexOf(this.vr.turn);
557 // Update current game object:
558 this.game.moves.push(move);
559 this.game.fen = move.fen;
560 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
561 this.game.initime[nextIdx] = Date.now();
562 // If repetition detected, consider that a draw offer was received:
563 const fenObj = V.ParseFen(move.fen);
564 let repIdx = fenObj.position + "_" + fenObj.turn;
566 repIdx += "_" + fenObj.flags;
567 this.repeat[repIdx] = (!!this.repeat[repIdx]
568 ? this.repeat[repIdx]+1
570 if (this.repeat[repIdx] >= 3)
571 this.drawOffer = "threerep";
572 else if (this.drawOffer == "threerep")
574 // Since corr games are stored at only one location, update should be
575 // done only by one player for each move:
576 if (!!this.game.mycolor &&
577 (this.game.type == "live" || move.color == this.game.mycolor))
580 switch (this.drawOffer)
586 drawCode = this.game.mycolor;
589 drawCode = this.vr.turn;
592 if (this.game.type == "corr")
594 GameStorage.update(this.gameRef.id,
599 squares: filtered_move,
600 played: Date.now(), //TODO: on server?
601 idx: this.game.moves.length - 1,
608 GameStorage.update(this.gameRef.id,
612 clocks: this.game.clocks,
613 initime: this.game.initime,
619 resetChatColor: function() {
620 // TODO: this is called twice, once on opening an once on closing
621 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
623 processChat: function(chat) {
624 this.st.conn.send(JSON.stringify({code:"newchat", chat:chat}));
625 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
626 if (this.game.type == "corr" && this.st.user.id > 0)
627 GameStorage.update(this.gameRef.id, {chat: chat});
629 gameOver: function(score, scoreMsg) {
630 this.game.score = score;
631 this.game.scoreMsg = this.st.tr[(!!scoreMsg
633 : getScoreMessage(score))];
634 const myIdx = this.game.players.findIndex(p => {
635 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
637 if (myIdx >= 0) //OK, I play in this game
639 GameStorage.update(this.gameRef.id,
640 {score: score, scoreMsg: scoreMsg});
647 <style lang="sass" scoped>
649 background-color: lightgreen
658 @media screen and (min-width: 768px)
661 @media screen and (max-width: 767px)
666 display: inline-block
669 display: inline-block
672 @media screen and (max-width: 767px)
675 @media screen and (min-width: 768px)
689 display: inline-block
693 display: inline-block
704 .draw-sent, .draw-sent:hover
705 background-color: lightyellow
707 .draw-received, .draw-received:hover
708 background-color: lightgreen
710 .draw-threerep, .draw-threerep:hover
711 background-color: #e4d1fc