3 input#modalChat.modal(type="checkbox" @click="resetChatColor()")
4 div#chatWrap(role="dialog" data-checkbox="modalChat")
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" @newmove="processMove" @gameover="gameOver")
37 import BaseGame from "@/components/BaseGame.vue";
38 import Chat from "@/components/Chat.vue";
39 import { store } from "@/store";
40 import { GameStorage } from "@/utils/gameStorage";
41 import { ppt } from "@/utils/datetime";
42 import { extractTime } from "@/utils/timeControl";
43 import { getRandString } from "@/utils/alea";
44 import { ArrayFun } from "@/utils/array";
45 import { processModalClick } from "@/utils/modalClick";
46 import { getScoreMessage } from "@/utils/scoring";
47 import params from "@/parameters";
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:""}],
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 // Related to (killing of) self multi-connects:
82 "$route": function(to, from) {
83 this.gameRef.id = to.params["id"];
84 this.gameRef.rid = to.query["rid"];
87 "game.clocks": function(newState) {
88 if (this.game.moves.length < 2 || this.game.score != "*")
90 // 1st move not completed yet, or game over: freeze time
91 this.virtualClocks = newState.map(s => ppt(s));
94 const currentTurn = this.vr.turn;
95 const colorIdx = ["w","b"].indexOf(currentTurn);
96 let countdown = newState[colorIdx] -
97 (Date.now() - this.game.initime[colorIdx])/1000;
98 this.virtualClocks = [0,1].map(i => {
99 const removeTime = i == colorIdx
100 ? (Date.now() - this.game.initime[colorIdx])/1000
102 return ppt(newState[i] - removeTime);
104 let clockUpdate = setInterval(() => {
105 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
107 clearInterval(clockUpdate);
109 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
112 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
116 // NOTE: some redundant code with Hall.vue (mostly related to people array)
117 created: function() {
118 // Always add myself to players' list
119 const my = this.st.user;
120 this.$set(this.people, my.sid, {id:my.id, name:my.name});
121 this.gameRef.id = this.$route.params["id"];
122 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
123 // Initialize connection
124 this.connexionString = params.socketUrl +
125 "/?sid=" + this.st.user.sid +
126 "&tmpId=" + getRandString() +
127 "&page=" + encodeURIComponent(this.$route.path);
128 this.conn = new WebSocket(this.connexionString);
129 this.conn.onmessage = this.socketMessageListener;
130 this.conn.onclose = this.socketCloseListener;
131 // Socket init required before loading remote game:
132 const socketInit = (callback) => {
133 if (!!this.conn && this.conn.readyState == 1) //1 == OPEN state
135 else //socket not ready yet (initial loading)
137 // NOTE: it's important to call callback without arguments,
138 // otherwise first arg is Websocket object and loadGame fails.
139 this.conn.onopen = () => { return 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.send("disconnect");
160 roomInit: function() {
161 // Notify the room only now that I connected, because
162 // messages might be lost otherwise (if game loading is slow)
163 this.send("connect");
164 this.send("pollclients");
166 send: function(code, obj) {
169 this.conn.send(JSON.stringify(
177 isConnected: function(index) {
178 const player = this.game.players[index];
180 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
182 // Try to find a match in people:
183 return Object.keys(this.people).some(sid => sid == player.sid) ||
184 Object.values(this.people).some(p => p.id == player.uid);
186 socketMessageListener: function(msg) {
189 const data = JSON.parse(msg.data);
193 data.sockIds.forEach(sid => {
194 this.$set(this.people, sid, {id:0, name:""});
195 if (sid != this.st.user.sid)
197 this.send("askidentity", {target:sid});
198 // Ask potentially missed last state, if opponent and I play
199 if (!!this.game.mycolor
200 && this.game.type == "live" && this.game.score == "*"
201 && this.game.players.some(p => p.sid == sid))
203 this.send("asklastate", {target:sid});
209 if (!this.people[data.from])
210 this.$set(this.people, data.from, {name:"", id:0});
211 if (!this.people[data.from].name)
213 this.newConnect[data.from] = true; //for self multi-connects tests
214 this.send("askidentity", {target:data.from});
218 this.$delete(this.people, data.from);
221 // I logged in elsewhere:
222 alert(this.st.tr["New connexion detected: tab now offline"]);
223 // TODO: this fails. See https://github.com/websockets/ws/issues/489
224 //this.conn.removeEventListener("message", this.socketMessageListener);
225 //this.conn.removeEventListener("close", this.socketCloseListener);
231 // Request for identification (TODO: anonymous shouldn't need to reply)
233 // Decompose to avoid revealing email
234 name: this.st.user.name,
235 sid: this.st.user.sid,
238 this.send("identity", {data:me, target:data.from});
243 const user = data.data;
244 if (!!user.name) //otherwise anonymous
246 // If I multi-connect, kill current connexion if no mark (I'm older)
247 if (this.newConnect[user.sid] && user.id > 0
248 && user.id == this.st.user.id && user.sid != this.st.user.sid)
250 if (!this.killed[this.st.user.sid])
252 this.send("killme", {sid:this.st.user.sid});
253 this.killed[this.st.user.sid] = true;
256 if (user.sid != this.st.user.sid) //I already know my identity...
258 this.$set(this.people, user.sid,
265 delete this.newConnect[user.sid];
269 // Send current (live) game if not asked by any of the players
270 if (this.game.type == "live"
271 && this.game.players.every(p => p.sid != data.from[0]))
276 players: this.game.players,
278 cadence: this.game.cadence,
279 score: this.game.score,
280 rid: this.st.user.sid, //useful in Hall if I'm an observer
282 this.send("game", {data:myGame, target:data.from});
286 this.send("fullgame", {data:this.game, target:data.from});
289 // Callback "roomInit" to poll clients only after game is loaded
290 this.loadGame(data.data, this.roomInit);
293 // Sending last state if I played a move or score != "*"
294 if ((this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
295 || this.game.score != "*" || this.drawOffer == "sent")
297 // Send our "last state" informations to opponent
298 const L = this.game.moves.length;
299 const myIdx = ["w","b"].indexOf(this.game.mycolor);
301 // NOTE: lastMove (when defined) includes addTime
302 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
303 // Since we played a move (or abort or resign),
304 // only drawOffer=="sent" is possible
305 drawSent: this.drawOffer == "sent",
306 score: this.game.score,
308 initime: this.game.initime[1-myIdx], //relevant only if I played
310 this.send("lastate", {data:myLastate, target:data.from});
313 case "lastate": //got opponent infos about last move
314 this.lastate = data.data;
315 if (this.game.rendered) //game is rendered (Board component)
316 this.processLastate();
317 //else: will be processed when game is ready
321 const move = data.data;
322 if (!!move.cancelDrawOffer) //opponent refuses draw
325 // NOTE for corr games: drawOffer reset by player in turn
326 if (this.game.type == "live" && !!this.game.mycolor)
327 GameStorage.update(this.gameRef.id, {drawOffer: ""});
329 this.$set(this.game, "moveToPlay", move);
333 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
336 this.gameOver("?", "Abort");
339 this.gameOver("1/2", data.data);
342 // NOTE: observers don't know who offered draw
343 this.drawOffer = "received";
346 this.newChat = data.data;
347 if (!document.getElementById("modalChat").checked)
348 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
352 socketCloseListener: function() {
353 this.conn = new WebSocket(this.connexionString);
354 this.conn.addEventListener('message', this.socketMessageListener);
355 this.conn.addEventListener('close', this.socketCloseListener);
357 // lastate was received, but maybe game wasn't ready yet:
358 processLastate: function() {
359 const data = this.lastate;
360 this.lastate = undefined; //security...
361 const L = this.game.moves.length;
362 if (data.movesCount > L)
364 // Just got last move from him
365 this.$set(this.game, "moveToPlay", Object.assign({initime: data.initime}, data.lastMove));
368 this.drawOffer = "received";
369 if (data.score != "*")
372 if (this.game.score == "*")
373 this.gameOver(data.score);
376 clickDraw: function() {
377 if (!this.game.mycolor)
378 return; //I'm just spectator
379 if (["received","threerep"].includes(this.drawOffer))
381 if (!confirm(this.st.tr["Accept draw?"]))
383 const message = (this.drawOffer == "received"
385 : "Three repetitions");
386 this.send("draw", {data:message});
387 this.gameOver("1/2", message);
389 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
391 if (this.game.mycolor != this.vr.turn)
392 return alert(this.st.tr["Draw offer only in your turn"]);
393 if (!confirm(this.st.tr["Offer draw?"]))
395 this.drawOffer = "sent";
396 this.send("drawoffer");
397 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
400 abortGame: function() {
401 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
403 this.gameOver("?", "Abort");
406 resign: function(e) {
407 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
409 this.send("resign", {data:this.game.mycolor});
410 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
412 // 3 cases for loading a game:
413 // - from indexedDB (running or completed live game I play)
414 // - from server (one correspondance game I play[ed] or not)
415 // - from remote peer (one live game I don't play, finished or not)
416 loadGame: function(game, callback) {
417 const afterRetrieval = async (game) => {
418 const vModule = await import("@/variants/" + game.vname + ".js");
419 window.V = vModule.VariantRules;
420 this.vr = new V(game.fen);
421 const gtype = (game.cadence.indexOf('d') >= 0 ? "corr" : "live");
422 const tc = extractTime(game.cadence);
424 game.chats = []; //live games don't have chat history
427 if (game.players[0].color == "b")
429 // Adopt the same convention for live and corr games: [0] = white
430 [ game.players[0], game.players[1] ] =
431 [ game.players[1], game.players[0] ];
433 // corr game: needs to compute the clocks + initime
434 // NOTE: clocks in seconds, initime in milliseconds
435 game.clocks = [tc.mainTime, tc.mainTime];
436 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
437 if (game.score == "*") //otherwise no need to bother with time
439 game.initime = [0, 0];
440 const L = game.moves.length;
443 let addTime = [0, 0];
444 for (let i=2; i<L; i++)
446 addTime[i%2] += tc.increment -
447 (game.moves[i].played - game.moves[i-1].played) / 1000;
449 for (let i=0; i<=1; i++)
450 game.clocks[i] += addTime[i];
453 game.initime[L%2] = game.moves[L-1].played;
455 // Now that we used idx and played, re-format moves as for live games
456 game.moves = game.moves.map( (m) => {
465 // Also sort chat messages (if any)
466 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
468 const myIdx = game.players.findIndex(p => {
469 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
471 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
473 game.clocks = [tc.mainTime, tc.mainTime];
474 if (game.score == "*")
476 game.initime[0] = Date.now();
479 // I play in this live game; corr games don't have clocks+initime
480 GameStorage.update(game.id,
483 initime: game.initime,
488 if (!!game.drawOffer)
490 if (game.drawOffer == "t") //three repetitions
491 this.drawOffer = "threerep";
495 this.drawOffer = "received"; //by any of the players
498 // I play in this game:
499 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
500 this.drawOffer = "sent";
501 else //all other cases
502 this.drawOffer = "received";
507 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
508 this.game = Object.assign({},
510 // NOTE: assign mycolor here, since BaseGame could also be VS computer
513 increment: tc.increment,
514 mycolor: [undefined,"w","b"][myIdx+1],
515 // opponent sid not strictly required (or available), but easier
516 // at least oppsid or oppid is available anyway:
517 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
518 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
521 this.$nextTick(() => {
522 this.game.rendered = true;
523 // Did lastate arrive before game was rendered?
525 this.processLastate();
527 this.repeat = {}; //reset: scan past moves' FEN:
529 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
530 let vr_tmp = new V(game.fenStart);
531 game.moves.forEach(m => {
533 const fenObj = V.ParseFen( vr_tmp.getFen() );
534 repIdx = fenObj.position + "_" + fenObj.turn;
536 repIdx += "_" + fenObj.flags;
537 this.repeat[repIdx] = (!!this.repeat[repIdx]
538 ? this.repeat[repIdx]+1
541 if (this.repeat[repIdx] >= 3)
542 this.drawOffer = "threerep";
547 return afterRetrieval(game);
548 if (!!this.gameRef.rid)
550 // Remote live game: forgetting about callback func... (TODO: design)
551 this.send("askfullgame", {target:this.gameRef.rid});
555 // Local or corr game
556 GameStorage.get(this.gameRef.id, afterRetrieval);
559 // Post-process a move (which was just played in BaseGame)
560 processMove: function(move) {
561 if (this.game.type == "corr" && move.color == this.game.mycolor)
563 if (!confirm(this.st.tr["Move played:"] + " " + move.notation + "\n" + this.st.tr["Are you sure?"]))
564 return this.$set(this.game, "moveToUndo", move);
566 // Update storage (corr or live) if I play in the game
567 const colorIdx = ["w","b"].indexOf(move.color);
568 const nextIdx = ["w","b"].indexOf(this.vr.turn);
569 // https://stackoverflow.com/a/38750895
570 if (!!this.game.mycolor)
572 const allowed_fields = ["appear", "vanish", "start", "end"];
573 // NOTE: 'var' to see this variable outside this block
574 var filtered_move = Object.keys(move)
575 .filter(key => allowed_fields.includes(key))
576 .reduce((obj, key) => {
577 obj[key] = move[key];
581 // Send move ("newmove" event) to people in the room (if our turn)
583 if (move.color == this.game.mycolor)
585 if (this.drawOffer == "received") //I refuse draw
587 if (this.game.moves.length >= 2) //after first move
589 const elapsed = Date.now() - this.game.initime[colorIdx];
590 // elapsed time is measured in milliseconds
591 addTime = this.game.increment - elapsed/1000;
593 const sendMove = Object.assign({},
597 cancelDrawOffer: this.drawOffer=="",
599 this.send("newmove", {data: sendMove});
600 // (Add)Time indication: useful in case of lastate infos requested
601 move.addTime = addTime;
604 addTime = move.addTime; //supposed transmitted
605 // Update current game object:
606 this.game.moves.push(move);
607 this.game.fen = move.fen;
608 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
609 // move.initime is set only when I receive a "lastate" move from opponent
610 this.game.initime[nextIdx] = move.initime || Date.now();
611 // If repetition detected, consider that a draw offer was received:
612 const fenObj = V.ParseFen(move.fen);
613 let repIdx = fenObj.position + "_" + fenObj.turn;
615 repIdx += "_" + fenObj.flags;
616 this.repeat[repIdx] = (!!this.repeat[repIdx]
617 ? this.repeat[repIdx]+1
619 if (this.repeat[repIdx] >= 3)
620 this.drawOffer = "threerep";
621 else if (this.drawOffer == "threerep")
623 // Since corr games are stored at only one location, update should be
624 // done only by one player for each move:
625 if (!!this.game.mycolor &&
626 (this.game.type == "live" || move.color == this.game.mycolor))
629 switch (this.drawOffer)
635 drawCode = this.game.mycolor;
638 drawCode = this.vr.turn;
641 if (this.game.type == "corr")
643 GameStorage.update(this.gameRef.id,
648 squares: filtered_move,
650 idx: this.game.moves.length - 1,
652 drawOffer: drawCode || "n", //"n" for "None" to force reset (otherwise it's ignored)
657 GameStorage.update(this.gameRef.id,
661 clocks: this.game.clocks,
662 initime: this.game.initime,
668 resetChatColor: function() {
669 // TODO: this is called twice, once on opening an once on closing
670 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
672 processChat: function(chat) {
673 this.send("newchat", {data:chat});
674 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
675 if (this.game.type == "corr" && this.st.user.id > 0)
676 GameStorage.update(this.gameRef.id, {chat: chat});
678 gameOver: function(score, scoreMsg) {
679 this.game.score = score;
680 this.game.scoreMsg = this.st.tr[(!!scoreMsg
682 : getScoreMessage(score))];
683 const myIdx = this.game.players.findIndex(p => {
684 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
686 if (myIdx >= 0) //OK, I play in this game
688 GameStorage.update(this.gameRef.id,
689 {score: score, scoreMsg: scoreMsg});
690 // Notify the score to main Hall. TODO: only one player (currently double send)
691 this.send("result", {gid:this.game.id, score:score});
698 <style lang="sass" scoped>
700 background-color: lightgreen
712 @media screen and (min-width: 768px)
715 @media screen and (max-width: 767px)
720 display: inline-block
723 display: inline-block
726 @media screen and (max-width: 767px)
729 @media screen and (min-width: 768px)
743 display: inline-block
747 display: inline-block
758 .draw-sent, .draw-sent:hover
759 background-color: lightyellow
761 .draw-received, .draw-received:hover
762 background-color: lightgreen
764 .draw-threerep, .draw-threerep:hover
765 background-color: #e4d1fc