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
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
75 "$route": function(to, from) {
76 this.gameRef.id = to.params["id"];
77 this.gameRef.rid = to.query["rid"];
80 "game.clocks": function(newState) {
81 if (this.game.moves.length < 2 || this.game.score != "*")
83 // 1st move not completed yet, or game over: freeze time
84 this.virtualClocks = newState.map(s => ppt(s));
87 const currentTurn = this.vr.turn;
88 const colorIdx = ["w","b"].indexOf(currentTurn);
89 let countdown = newState[colorIdx] -
90 (Date.now() - this.game.initime[colorIdx])/1000;
91 this.virtualClocks = [0,1].map(i => {
92 const removeTime = i == colorIdx
93 ? (Date.now() - this.game.initime[colorIdx])/1000
95 return ppt(newState[i] - removeTime);
97 let clockUpdate = setInterval(() => {
98 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
100 clearInterval(clockUpdate);
102 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
105 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
109 // NOTE: some redundant code with Hall.vue (related to people array)
110 created: function() {
111 // Always add myself to players' list
112 const my = this.st.user;
113 this.$set(this.people, my.sid, {id:my.id, name:my.name});
114 this.gameRef.id = this.$route.params["id"];
115 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
116 // Define socket .onmessage() and .onclose() events:
117 this.st.conn.onmessage = this.socketMessageListener;
118 const socketCloseListener = () => {
119 store.socketCloseListener(); //reinitialize connexion (in store.js)
120 this.st.conn.addEventListener('message', this.socketMessageListener);
121 this.st.conn.addEventListener('close', socketCloseListener);
123 this.st.conn.onclose = socketCloseListener;
124 // Socket init required before loading remote game:
125 const socketInit = (callback) => {
126 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
128 else //socket not ready yet (initial loading)
129 this.st.conn.onopen = callback;
131 if (!this.gameRef.rid) //game stored locally or on server
132 this.loadGame(null, () => socketInit(this.roomInit));
133 else //game stored remotely: need socket to retrieve it
135 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
136 // --> It will be given when receiving "fullgame" socket event.
137 // A more general approach would be to store it somewhere.
138 socketInit(this.loadGame);
141 mounted: function() {
142 document.getElementById("chatWrap").addEventListener(
143 "click", processModalClick);
146 // O.1] Ask server for room composition:
147 roomInit: function() {
148 // Notify the room only now that I connected, because
149 // messages might be lost otherwise (if game loading is slow)
150 this.st.conn.send(JSON.stringify({code:"connect"}));
151 this.st.conn.send(JSON.stringify({code:"pollclients"}));
153 isConnected: function(index) {
154 const name = this.game.players[index].name;
155 if (this.st.user.name == name)
157 return Object.values(this.people).some(p => p.name == name);
159 socketMessageListener: function(msg) {
160 const data = JSON.parse(msg.data);
164 alert(this.st.tr["Warning: multi-tabs not supported"]);
166 // 0.2] Receive clients list (just socket IDs)
169 data.sockIds.forEach(sid => {
170 if (!!this.people[sid])
172 this.$set(this.people, sid, {id:0, name:""});
174 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
180 // Request for identification: reply if I'm not anonymous
181 if (this.st.user.id > 0)
183 this.st.conn.send(JSON.stringify({code:"identity",
185 // NOTE: decompose to avoid revealing email
186 name: this.st.user.name,
187 sid: this.st.user.sid,
196 // NOTE: sometimes player.id fails because player is undefined...
197 // Probably because the event was meant for Hall?
198 if (!this.people[data.user.sid])
200 this.$set(this.people, data.user.sid,
201 {id: data.user.id, name: data.user.name});
202 // Sending last state only for live games: corr games are complete,
203 // only if I played a move (otherwise opponent has all)
204 if (!!this.game.mycolor && this.game.type == "live"
205 && this.game.oppsid == data.user.sid
206 && this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
208 // Send our "last state" informations to opponent
209 const L = this.game.moves.length;
210 this.st.conn.send(JSON.stringify({
212 target: data.user.sid,
215 lastMove: this.game.moves[L-1],
216 // Since we played a move, only drawOffer=="sent" is possible
217 drawSent: this.drawOffer == "sent",
218 score: this.game.score,
220 clocks: this.game.clocks,
227 // Send current (live) game if I play in (not an observer),
228 // and not asked by opponent (!)
229 if (this.game.type == "live"
230 && this.game.players.some(p => p.sid == this.st.user.sid)
231 && this.game.players.every(p => p.sid != data.from))
235 // Minimal game informations:
237 players: this.game.players,
239 timeControl: this.game.timeControl,
241 this.st.conn.send(JSON.stringify({code:"game",
242 game:myGame, target:data.from}));
246 if (!!data.move.cancelDrawOffer) //opponent refuses draw
248 this.$set(this.game, "moveToPlay", data.move);
251 this.newChat = data.chat;
252 if (!document.getElementById("modalChat").checked)
253 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
255 case "lastate": //got opponent infos about last move
258 if (!!this.game.type) //game is loaded
259 this.processLastate();
260 //else: will be processed when game is ready
264 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
267 this.gameOver("?", "Abort");
270 this.gameOver("1/2", data.message);
273 // NOTE: observers don't know who offered draw
274 this.drawOffer = "received";
277 this.st.conn.send(JSON.stringify({code:"fullgame",
278 game:this.game, target:data.from}));
281 // Callback "roomInit" to poll clients only after game is loaded
282 this.loadGame(data.game, this.roomInit);
286 // TODO: next condition is probably not required. See note line 150
287 if (!this.people[data.from])
289 this.$set(this.people, data.from, {name:"", id:0});
290 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
295 this.$delete(this.people, data.from);
299 // lastate was received, but maybe game wasn't ready yet:
300 processLastate: function() {
301 const data = this.lastate;
302 this.lastate = undefined; //security...
303 const L = this.game.moves.length;
304 if (data.movesCount > L)
306 // Just got last move from him
307 if (data.score != "*" && this.game.score == "*")
308 this.gameOver(data.score);
309 this.game.clocks = data.clocks; //TODO: check this?
311 this.drawOffer = "received";
312 this.$set(this.game, "moveToPlay", data.lastMove);
315 clickDraw: function() {
316 if (!this.game.mycolor)
317 return; //I'm just spectator
318 if (["received","threerep"].includes(this.drawOffer))
320 if (!confirm(this.st.tr["Accept draw?"]))
322 const message = (this.drawOffer == "received"
324 : "Three repetitions");
325 Object.keys(this.people).forEach(sid => {
326 if (sid != this.st.user.sid)
328 this.st.conn.send(JSON.stringify({code:"draw",
329 message:message, target:sid}));
332 this.gameOver("1/2", message);
334 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
336 if (this.game.mycolor != this.vr.turn)
337 return alert(this.st.tr["Draw offer only in your turn"]);
338 if (!confirm(this.st.tr["Offer draw?"]))
340 this.drawOffer = "sent";
341 Object.keys(this.people).forEach(sid => {
342 if (sid != this.st.user.sid)
343 this.st.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
345 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
348 abortGame: function() {
349 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
351 this.gameOver("?", "Abort");
352 Object.keys(this.people).forEach(sid => {
353 if (sid != this.st.user.sid)
355 this.st.conn.send(JSON.stringify({
362 resign: function(e) {
363 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
365 Object.keys(this.people).forEach(sid => {
366 if (sid != this.st.user.sid)
368 this.st.conn.send(JSON.stringify({code:"resign",
369 side:this.game.mycolor, target:sid}));
372 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
374 // 3 cases for loading a game:
375 // - from indexedDB (running or completed live game I play)
376 // - from server (one correspondance game I play[ed] or not)
377 // - from remote peer (one live game I don't play, finished or not)
378 loadGame: function(game, callback) {
379 const afterRetrieval = async (game) => {
380 const vModule = await import("@/variants/" + game.vname + ".js");
381 window.V = vModule.VariantRules;
382 this.vr = new V(game.fen);
383 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
384 const tc = extractTime(game.timeControl);
387 if (game.players[0].color == "b")
389 // Adopt the same convention for live and corr games: [0] = white
390 [ game.players[0], game.players[1] ] =
391 [ game.players[1], game.players[0] ];
393 // corr game: needs to compute the clocks + initime
394 // NOTE: clocks in seconds, initime in milliseconds
395 game.clocks = [tc.mainTime, tc.mainTime];
396 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
397 if (game.score == "*") //otherwise no need to bother with time
399 game.initime = [0, 0];
400 const L = game.moves.length;
403 let addTime = [0, 0];
404 for (let i=2; i<L; i++)
406 addTime[i%2] += tc.increment -
407 (game.moves[i].played - game.moves[i-1].played) / 1000;
409 for (let i=0; i<=1; i++)
410 game.clocks[i] += addTime[i];
413 game.initime[L%2] = game.moves[L-1].played;
415 // Now that we used idx and played, re-format moves as for live games
416 game.moves = game.moves.map( (m) => {
425 // Also sort chat messages (if any)
426 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
428 const myIdx = game.players.findIndex(p => {
429 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
431 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
433 game.clocks = [tc.mainTime, tc.mainTime];
434 if (game.score == "*")
436 game.initime[0] = Date.now();
439 // I play in this live game; corr games don't have clocks+initime
440 GameStorage.update(game.id,
443 initime: game.initime,
448 if (!!game.drawOffer)
450 if (game.drawOffer == "t") //three repetitions
451 this.drawOffer = "threerep";
455 this.drawOffer = "received"; //by any of the players
458 // I play in this game:
459 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
460 this.drawOffer = "sent";
461 else //all other cases
462 this.drawOffer = "received";
467 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
468 this.game = Object.assign({},
470 // NOTE: assign mycolor here, since BaseGame could also be VS computer
473 increment: tc.increment,
474 mycolor: [undefined,"w","b"][myIdx+1],
475 // opponent sid not strictly required (or available), but easier
476 // at least oppsid or oppid is available anyway:
477 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
478 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
481 this.repeat = {}; //reset: scan past moves' FEN:
483 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
484 let vr_tmp = new V(game.fenStart);
485 game.moves.forEach(m => {
487 const fenObj = V.ParseFen( vr_tmp.getFen() );
488 repIdx = fenObj.position + "_" + fenObj.turn;
490 repIdx += "_" + fenObj.flags;
491 this.repeat[repIdx] = (!!this.repeat[repIdx]
492 ? this.repeat[repIdx]+1
495 if (this.repeat[repIdx] >= 3)
496 this.drawOffer = "threerep";
497 if (!!this.lastate) //lastate arrived before game was loaded:
498 this.processLastate();
502 return afterRetrieval(game);
503 if (!!this.gameRef.rid)
505 // Remote live game: forgetting about callback func... (TODO: design)
506 this.st.conn.send(JSON.stringify(
507 {code:"askfullgame", target:this.gameRef.rid}));
511 // Local or corr game
512 GameStorage.get(this.gameRef.id, afterRetrieval);
515 // Post-process a move (which was just played)
516 processMove: function(move) {
517 // Update storage (corr or live) if I play in the game
518 const colorIdx = ["w","b"].indexOf(move.color);
519 // https://stackoverflow.com/a/38750895
520 if (!!this.game.mycolor)
522 const allowed_fields = ["appear", "vanish", "start", "end"];
523 // NOTE: 'var' to see this variable outside this block
524 var filtered_move = Object.keys(move)
525 .filter(key => allowed_fields.includes(key))
526 .reduce((obj, key) => {
527 obj[key] = move[key];
531 // Send move ("newmove" event) to people in the room (if our turn)
533 if (move.color == this.game.mycolor)
535 if (this.drawOffer == "received") //I refuse draw
537 if (this.game.moves.length >= 2) //after first move
539 const elapsed = Date.now() - this.game.initime[colorIdx];
540 // elapsed time is measured in milliseconds
541 addTime = this.game.increment - elapsed/1000;
543 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
544 Object.keys(this.people).forEach(sid => {
545 if (sid != this.st.user.sid)
547 this.st.conn.send(JSON.stringify({
551 cancelDrawOffer: this.drawOffer=="",
557 addTime = move.addTime; //supposed transmitted
558 const nextIdx = ["w","b"].indexOf(this.vr.turn);
559 // Update current game object:
560 this.game.moves.push(move);
561 this.game.fen = move.fen;
562 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
563 this.game.initime[nextIdx] = Date.now();
564 // If repetition detected, consider that a draw offer was received:
565 const fenObj = V.ParseFen(move.fen);
566 let repIdx = fenObj.position + "_" + fenObj.turn;
568 repIdx += "_" + fenObj.flags;
569 this.repeat[repIdx] = (!!this.repeat[repIdx]
570 ? this.repeat[repIdx]+1
572 if (this.repeat[repIdx] >= 3)
573 this.drawOffer = "threerep";
574 else if (this.drawOffer == "threerep")
576 // Since corr games are stored at only one location, update should be
577 // done only by one player for each move:
578 if (!!this.game.mycolor &&
579 (this.game.type == "live" || move.color == this.game.mycolor))
582 switch (this.drawOffer)
588 drawCode = this.game.mycolor;
591 drawCode = this.vr.turn;
594 if (this.game.type == "corr")
596 GameStorage.update(this.gameRef.id,
601 squares: filtered_move,
602 played: Date.now(), //TODO: on server?
603 idx: this.game.moves.length - 1,
610 GameStorage.update(this.gameRef.id,
614 clocks: this.game.clocks,
615 initime: this.game.initime,
621 resetChatColor: function() {
622 // TODO: this is called twice, once on opening an once on closing
623 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
625 processChat: function(chat) {
626 this.st.conn.send(JSON.stringify({code:"newchat", chat:chat}));
627 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
628 if (this.game.type == "corr" && this.st.user.id > 0)
629 GameStorage.update(this.gameRef.id, {chat: chat});
631 gameOver: function(score, scoreMsg) {
632 this.game.score = score;
633 this.game.scoreMsg = this.st.tr[(!!scoreMsg
635 : getScoreMessage(score))];
636 const myIdx = this.game.players.findIndex(p => {
637 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
639 if (myIdx >= 0) //OK, I play in this game
641 GameStorage.update(this.gameRef.id,
642 {score: score, scoreMsg: scoreMsg});
649 <style lang="sass" scoped>
651 background-color: lightgreen
660 @media screen and (min-width: 768px)
663 @media screen and (max-width: 767px)
668 display: inline-block
671 display: inline-block
674 @media screen and (max-width: 767px)
677 @media screen and (min-width: 768px)
692 display: inline-block
696 display: inline-block
707 .draw-sent, .draw-sent:hover
708 background-color: lightyellow
710 .draw-received, .draw-received:hover
711 background-color: lightgreen
713 .draw-threerep, .draw-threerep:hover
714 background-color: #e4d1fc