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" 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 { getRandString } from "@/utils/alea";
45 import { ArrayFun } from "@/utils/array";
46 import { processModalClick } from "@/utils/modalClick";
47 import { getScoreMessage } from "@/utils/scoring";
48 import params from "@/parameters";
55 // gameRef: to find the game in (potentially remote) storage
59 gameRef: { //given in URL (rid = remote ID)
63 game: { //passed to BaseGame
64 players:[{name:""},{name:""}],
68 virtualClocks: [0, 0], //initialized with true game.clocks
69 vr: null, //"variant rules" object initialized from FEN
71 people: {}, //players + observers
72 lastate: undefined, //used if opponent send lastate before game is ready
73 repeat: {}, //detect position repetition
77 // Related to (killing of) self multi-connects:
83 "$route": function(to, from) {
84 this.gameRef.id = to.params["id"];
85 this.gameRef.rid = to.query["rid"];
88 "game.clocks": function(newState) {
89 if (this.game.moves.length < 2 || this.game.score != "*")
91 // 1st move not completed yet, or game over: freeze time
92 this.virtualClocks = newState.map(s => ppt(s));
95 const currentTurn = this.vr.turn;
96 const colorIdx = ["w","b"].indexOf(currentTurn);
97 let countdown = newState[colorIdx] -
98 (Date.now() - this.game.initime[colorIdx])/1000;
99 this.virtualClocks = [0,1].map(i => {
100 const removeTime = i == colorIdx
101 ? (Date.now() - this.game.initime[colorIdx])/1000
103 return ppt(newState[i] - removeTime);
105 let clockUpdate = setInterval(() => {
106 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
108 clearInterval(clockUpdate);
110 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
113 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
117 // NOTE: some redundant code with Hall.vue (mostly related to people array)
118 created: function() {
119 // Always add myself to players' list
120 const my = this.st.user;
121 this.$set(this.people, my.sid, {id:my.id, name:my.name});
122 this.gameRef.id = this.$route.params["id"];
123 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
124 // Initialize connection
125 this.connexionString = params.socketUrl +
126 "/?sid=" + this.st.user.sid +
127 "&tmpId=" + getRandString() +
128 "&page=" + encodeURIComponent(this.$route.path);
129 this.conn = new WebSocket(this.connexionString);
130 this.conn.onmessage = this.socketMessageListener;
131 this.conn.onclose = this.socketCloseListener;
132 // Socket init required before loading remote game:
133 const socketInit = (callback) => {
134 if (!!this.conn && this.conn.readyState == 1) //1 == OPEN state
136 else //socket not ready yet (initial loading)
138 // NOTE: it's important to call callback without arguments,
139 // otherwise first arg is Websocket object and loadGame fails.
140 this.conn.onopen = () => { return callback() };
143 if (!this.gameRef.rid) //game stored locally or on server
144 this.loadGame(null, () => socketInit(this.roomInit));
145 else //game stored remotely: need socket to retrieve it
147 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
148 // --> It will be given when receiving "fullgame" socket event.
149 // A more general approach would be to store it somewhere.
150 socketInit(this.loadGame);
153 mounted: function() {
154 document.getElementById("chatWrap").addEventListener(
155 "click", processModalClick);
157 beforeDestroy: function() {
158 this.send("disconnect");
161 roomInit: function() {
162 // Notify the room only now that I connected, because
163 // messages might be lost otherwise (if game loading is slow)
164 this.send("connect");
165 this.send("pollclients");
167 send: function(code, obj) {
170 this.conn.send(JSON.stringify(
178 isConnected: function(index) {
179 const player = this.game.players[index];
181 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
183 // Try to find a match in people:
184 return Object.keys(this.people).some(sid => sid == player.sid) ||
185 Object.values(this.people).some(p => p.id == player.uid);
187 socketMessageListener: function(msg) {
190 const data = JSON.parse(msg.data);
194 data.sockIds.forEach(sid => {
195 this.$set(this.people, sid, {id:0, name:""});
196 if (sid != this.st.user.sid)
198 this.send("askidentity", {target:sid});
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 == sid))
204 this.send("asklastate", {target:sid});
210 if (!this.people[data.from])
211 this.$set(this.people, data.from, {name:"", id:0});
212 if (!this.people[data.from].name)
214 this.newConnect[data.from] = true; //for self multi-connects tests
215 this.send("askidentity", {target:data.from});
219 this.$delete(this.people, data.from);
222 // I logged in elsewhere:
223 alert(this.st.tr["New connexion detected: tab now offline"]);
224 // TODO: this fails. See https://github.com/websockets/ws/issues/489
225 //this.conn.removeEventListener("message", this.socketMessageListener);
226 //this.conn.removeEventListener("close", this.socketCloseListener);
232 // Request for identification (TODO: anonymous shouldn't need to reply)
234 // Decompose to avoid revealing email
235 name: this.st.user.name,
236 sid: this.st.user.sid,
239 this.send("identity", {data:me, target:data.from});
244 const user = data.data;
245 if (!!user.name) //otherwise anonymous
247 // If I multi-connect, kill current connexion if no mark (I'm older)
248 if (this.newConnect[user.sid] && user.id > 0
249 && user.id == this.st.user.id && user.sid != this.st.user.sid)
251 if (!this.killed[this.st.user.sid])
253 this.send("killme", {sid:this.st.user.sid});
254 this.killed[this.st.user.sid] = true;
257 if (user.sid != this.st.user.sid) //I already know my identity...
259 this.$set(this.people, user.sid,
266 delete this.newConnect[user.sid];
270 // Send current (live) game if not asked by any of the players
271 if (this.game.type == "live"
272 && this.game.players.every(p => p.sid != data.from[0]))
277 players: this.game.players,
279 cadence: this.game.cadence,
280 score: this.game.score,
281 rid: this.st.user.sid, //useful in Hall if I'm an observer
283 this.send("game", {data:myGame, target:data.from});
287 this.send("fullgame", {data:this.game, target:data.from});
290 // Callback "roomInit" to poll clients only after game is loaded
291 this.loadGame(data.data, this.roomInit);
294 // Sending last state if I played a move or score != "*"
295 if ((this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
296 || this.game.score != "*" || this.drawOffer == "sent")
298 // Send our "last state" informations to opponent
299 const L = this.game.moves.length;
300 const myIdx = ["w","b"].indexOf(this.game.mycolor);
302 // NOTE: lastMove (when defined) includes addTime
303 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
304 // Since we played a move (or abort or resign),
305 // only drawOffer=="sent" is possible
306 drawSent: this.drawOffer == "sent",
307 score: this.game.score,
309 initime: this.game.initime[1-myIdx], //relevant only if I played
311 this.send("lastate", {data:myLastate, target:data.from});
314 case "lastate": //got opponent infos about last move
315 this.lastate = data.data;
316 if (this.game.rendered) //game is rendered (Board component)
317 this.processLastate();
318 //else: will be processed when game is ready
322 const move = data.data;
323 if (!!move.cancelDrawOffer) //opponent refuses draw
326 // NOTE for corr games: drawOffer reset by player in turn
327 if (this.game.type == "live" && !!this.game.mycolor)
328 GameStorage.update(this.gameRef.id, {drawOffer: ""});
330 this.$set(this.game, "moveToPlay", move);
334 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
337 this.gameOver("?", "Abort");
340 this.gameOver("1/2", data.data);
343 // NOTE: observers don't know who offered draw
344 this.drawOffer = "received";
348 const chat = data.data;
350 if (!document.getElementById("modalChat").checked)
351 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
356 socketCloseListener: function() {
357 this.conn = new WebSocket(this.connexionString);
358 this.conn.addEventListener('message', this.socketMessageListener);
359 this.conn.addEventListener('close', this.socketCloseListener);
361 // lastate was received, but maybe game wasn't ready yet:
362 processLastate: function() {
363 const data = this.lastate;
364 this.lastate = undefined; //security...
365 const L = this.game.moves.length;
366 if (data.movesCount > L)
368 // Just got last move from him
369 this.$set(this.game, "moveToPlay", Object.assign({initime: data.initime}, data.lastMove));
372 this.drawOffer = "received";
373 if (data.score != "*")
376 if (this.game.score == "*")
377 this.gameOver(data.score);
380 clickDraw: function() {
381 if (!this.game.mycolor)
382 return; //I'm just spectator
383 if (["received","threerep"].includes(this.drawOffer))
385 if (!confirm(this.st.tr["Accept draw?"]))
387 const message = (this.drawOffer == "received"
389 : "Three repetitions");
390 this.send("draw", {data:message});
391 this.gameOver("1/2", message);
393 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
395 if (this.game.mycolor != this.vr.turn)
396 return alert(this.st.tr["Draw offer only in your turn"]);
397 if (!confirm(this.st.tr["Offer draw?"]))
399 this.drawOffer = "sent";
400 this.send("drawoffer");
401 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
404 abortGame: function() {
405 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
407 this.gameOver("?", "Abort");
410 resign: function(e) {
411 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
413 this.send("resign", {data:this.game.mycolor});
414 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
416 // 3 cases for loading a game:
417 // - from indexedDB (running or completed live game I play)
418 // - from server (one correspondance game I play[ed] or not)
419 // - from remote peer (one live game I don't play, finished or not)
420 loadGame: function(game, callback) {
421 const afterRetrieval = async (game) => {
422 const vModule = await import("@/variants/" + game.vname + ".js");
423 window.V = vModule.VariantRules;
424 this.vr = new V(game.fen);
425 const gtype = (game.cadence.indexOf('d') >= 0 ? "corr" : "live");
426 const tc = extractTime(game.cadence);
428 game.chats = []; //live games don't have chat history
431 if (game.players[0].color == "b")
433 // Adopt the same convention for live and corr games: [0] = white
434 [ game.players[0], game.players[1] ] =
435 [ game.players[1], game.players[0] ];
437 // corr game: needs to compute the clocks + initime
438 // NOTE: clocks in seconds, initime in milliseconds
439 game.clocks = [tc.mainTime, tc.mainTime];
440 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
441 if (game.score == "*") //otherwise no need to bother with time
443 game.initime = [0, 0];
444 const L = game.moves.length;
447 let addTime = [0, 0];
448 for (let i=2; i<L; i++)
450 addTime[i%2] += tc.increment -
451 (game.moves[i].played - game.moves[i-1].played) / 1000;
453 for (let i=0; i<=1; i++)
454 game.clocks[i] += addTime[i];
457 game.initime[L%2] = game.moves[L-1].played;
459 // Now that we used idx and played, re-format moves as for live games
460 game.moves = game.moves.map( (m) => {
469 // Also sort chat messages (if any)
470 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
472 const myIdx = game.players.findIndex(p => {
473 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
475 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
477 game.clocks = [tc.mainTime, tc.mainTime];
478 if (game.score == "*")
480 game.initime[0] = Date.now();
483 // I play in this live game; corr games don't have clocks+initime
484 GameStorage.update(game.id,
487 initime: game.initime,
492 if (!!game.drawOffer)
494 if (game.drawOffer == "t") //three repetitions
495 this.drawOffer = "threerep";
499 this.drawOffer = "received"; //by any of the players
502 // I play in this game:
503 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
504 this.drawOffer = "sent";
505 else //all other cases
506 this.drawOffer = "received";
511 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
512 this.game = Object.assign({},
514 // NOTE: assign mycolor here, since BaseGame could also be VS computer
517 increment: tc.increment,
518 mycolor: [undefined,"w","b"][myIdx+1],
519 // opponent sid not strictly required (or available), but easier
520 // at least oppsid or oppid is available anyway:
521 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
522 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
525 this.$nextTick(() => {
526 this.game.rendered = true;
527 // Did lastate arrive before game was rendered?
529 this.processLastate();
531 this.repeat = {}; //reset: scan past moves' FEN:
533 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
534 let vr_tmp = new V(game.fenStart);
535 game.moves.forEach(m => {
537 const fenObj = V.ParseFen( vr_tmp.getFen() );
538 repIdx = fenObj.position + "_" + fenObj.turn;
540 repIdx += "_" + fenObj.flags;
541 this.repeat[repIdx] = (!!this.repeat[repIdx]
542 ? this.repeat[repIdx]+1
545 if (this.repeat[repIdx] >= 3)
546 this.drawOffer = "threerep";
551 return afterRetrieval(game);
552 if (!!this.gameRef.rid)
554 // Remote live game: forgetting about callback func... (TODO: design)
555 this.send("askfullgame", {target:this.gameRef.rid});
559 // Local or corr game
560 GameStorage.get(this.gameRef.id, afterRetrieval);
563 // Post-process a move (which was just played)
564 processMove: function(move) {
565 // Update storage (corr or live) if I play in the game
566 const colorIdx = ["w","b"].indexOf(move.color);
567 const nextIdx = ["w","b"].indexOf(this.vr.turn);
568 // https://stackoverflow.com/a/38750895
569 if (!!this.game.mycolor)
571 const allowed_fields = ["appear", "vanish", "start", "end"];
572 // NOTE: 'var' to see this variable outside this block
573 var filtered_move = Object.keys(move)
574 .filter(key => allowed_fields.includes(key))
575 .reduce((obj, key) => {
576 obj[key] = move[key];
580 // Send move ("newmove" event) to people in the room (if our turn)
582 if (move.color == this.game.mycolor)
584 if (this.drawOffer == "received") //I refuse draw
586 if (this.game.moves.length >= 2) //after first move
588 const elapsed = Date.now() - this.game.initime[colorIdx];
589 // elapsed time is measured in milliseconds
590 addTime = this.game.increment - elapsed/1000;
592 const sendMove = Object.assign({},
596 cancelDrawOffer: this.drawOffer=="",
598 this.send("newmove", {data: sendMove});
599 // (Add)Time indication: useful in case of lastate infos requested
600 move.addTime = addTime;
603 addTime = move.addTime; //supposed transmitted
604 // Update current game object:
605 this.game.moves.push(move);
606 this.game.fen = move.fen;
607 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
608 // move.initime is set only when I receive a "lastate" move from opponent
609 this.game.initime[nextIdx] = move.initime || Date.now();
610 // If repetition detected, consider that a draw offer was received:
611 const fenObj = V.ParseFen(move.fen);
612 let repIdx = fenObj.position + "_" + fenObj.turn;
614 repIdx += "_" + fenObj.flags;
615 this.repeat[repIdx] = (!!this.repeat[repIdx]
616 ? this.repeat[repIdx]+1
618 if (this.repeat[repIdx] >= 3)
619 this.drawOffer = "threerep";
620 else if (this.drawOffer == "threerep")
622 // Since corr games are stored at only one location, update should be
623 // done only by one player for each move:
624 if (!!this.game.mycolor &&
625 (this.game.type == "live" || move.color == this.game.mycolor))
628 switch (this.drawOffer)
634 drawCode = this.game.mycolor;
637 drawCode = this.vr.turn;
640 if (this.game.type == "corr")
642 GameStorage.update(this.gameRef.id,
647 squares: filtered_move,
649 idx: this.game.moves.length - 1,
651 drawOffer: drawCode || "n", //"n" for "None" to force reset (otherwise it's ignored)
656 GameStorage.update(this.gameRef.id,
660 clocks: this.game.clocks,
661 initime: this.game.initime,
667 resetChatColor: function() {
668 // TODO: this is called twice, once on opening an once on closing
669 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
671 processChat: function(chat) {
672 this.send("newchat", {data:chat});
673 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
674 if (this.game.type == "corr" && this.st.user.id > 0)
675 GameStorage.update(this.gameRef.id, {chat: chat});
677 gameOver: function(score, scoreMsg) {
678 this.game.score = score;
679 this.game.scoreMsg = this.st.tr[(!!scoreMsg
681 : getScoreMessage(score))];
682 const myIdx = this.game.players.findIndex(p => {
683 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
685 if (myIdx >= 0) //OK, I play in this game
687 GameStorage.update(this.gameRef.id,
688 {score: score, scoreMsg: scoreMsg});
695 <style lang="sass" scoped>
697 background-color: lightgreen
706 @media screen and (min-width: 768px)
709 @media screen and (max-width: 767px)
714 display: inline-block
717 display: inline-block
720 @media screen and (max-width: 767px)
723 @media screen and (min-width: 768px)
737 display: inline-block
741 display: inline-block
752 .draw-sent, .draw-sent:hover
753 background-color: lightyellow
755 .draw-received, .draw-received:hover
756 background-color: lightgreen
758 .draw-threerep, .draw-threerep:hover
759 background-color: #e4d1fc