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 { 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:""}],
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)
136 this.conn.onopen = callback;
138 if (!this.gameRef.rid) //game stored locally or on server
139 this.loadGame(null, () => socketInit(this.roomInit));
140 else //game stored remotely: need socket to retrieve it
142 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
143 // --> It will be given when receiving "fullgame" socket event.
144 // A more general approach would be to store it somewhere.
145 socketInit(this.loadGame);
148 mounted: function() {
149 document.getElementById("chatWrap").addEventListener(
150 "click", processModalClick);
152 beforeDestroy: function() {
153 this.send("disconnect");
156 roomInit: function() {
157 // Notify the room only now that I connected, because
158 // messages might be lost otherwise (if game loading is slow)
159 this.send("connect");
160 this.send("pollclients");
162 send: function(code, obj) {
165 this.conn.send(JSON.stringify(
173 isConnected: function(index) {
174 const player = this.game.players[index];
176 if (this.st.user.sid == player.sid || this.st.user.id == player.uid)
178 // Try to find a match in people:
179 return Object.keys(this.people).some(sid => sid == player.sid) ||
180 Object.values(this.people).some(p => p.id == player.uid);
182 socketMessageListener: function(msg) {
185 const data = JSON.parse(msg.data);
189 data.sockIds.forEach(sid => {
190 this.$set(this.people, sid, {id:0, name:""});
191 if (sid != this.st.user.sid)
193 this.send("askidentity", {target:sid});
194 // Ask potentially missed last state, if opponent and I play
195 if (!!this.game.mycolor
196 && this.game.type == "live" && this.game.score == "*"
197 && this.game.players.some(p => p.sid == sid))
199 this.send("asklastate", {target:sid});
205 if (!this.people[data.from])
206 this.$set(this.people, data.from, {name:"", id:0});
207 if (!this.people[data.from].name)
209 this.newConnect[data.from] = true; //for self multi-connects tests
210 this.send("askidentity", {target:data.from});
214 this.$delete(this.people, data.from);
217 // I logged in elsewhere:
218 alert(this.st.tr["New connexion detected: tab now offline"]);
219 // TODO: this fails. See https://github.com/websockets/ws/issues/489
220 //this.conn.removeEventListener("message", this.socketMessageListener);
221 //this.conn.removeEventListener("close", this.socketCloseListener);
227 // Request for identification (TODO: anonymous shouldn't need to reply)
229 // Decompose to avoid revealing email
230 name: this.st.user.name,
231 sid: this.st.user.sid,
234 this.send("identity", {data:me, target:data.from});
239 const user = data.data;
240 if (!!user.name) //otherwise anonymous
242 // If I multi-connect, kill current connexion if no mark (I'm older)
243 if (this.newConnect[user.sid] && user.id > 0
244 && user.id == this.st.user.id && user.sid != this.st.user.sid)
246 if (!this.killed[this.st.user.sid])
248 this.send("killme", {sid:this.st.user.sid});
249 this.killed[this.st.user.sid] = true;
252 if (user.sid != this.st.user.sid) //I already know my identity...
254 this.$set(this.people, user.sid,
261 delete this.newConnect[user.sid];
265 // Send current (live) game if not asked by any of the players
266 if (this.game.type == "live"
267 && this.game.players.every(p => p.sid != data.from[0]))
272 players: this.game.players,
274 cadence: this.game.cadence,
275 score: this.game.score,
276 rid: this.st.user.sid, //useful in Hall if I'm an observer
278 this.send("game", {data:myGame, target:data.from});
282 this.send("fullgame", {data:this.game, target:data.from});
285 // Callback "roomInit" to poll clients only after game is loaded
286 this.loadGame(data.data, this.roomInit);
289 // Sending last state if I played a move or score != "*"
290 if ((this.game.moves.length > 0 && this.vr.turn != this.game.mycolor)
291 || this.game.score != "*" || this.drawOffer == "sent")
293 // Send our "last state" informations to opponent
294 const L = this.game.moves.length;
295 const myIdx = ["w","b"].indexOf(this.game.mycolor);
297 // NOTE: lastMove (when defined) includes addTime
298 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
299 // Since we played a move (or abort or resign),
300 // only drawOffer=="sent" is possible
301 drawSent: this.drawOffer == "sent",
302 score: this.game.score,
304 initime: this.game.initime[1-myIdx], //relevant only if I played
306 this.send("lastate", {data:myLastate, target:data.from});
309 case "lastate": //got opponent infos about last move
310 this.lastate = data.data;
311 if (this.game.rendered) //game is rendered (Board component)
312 this.processLastate();
313 //else: will be processed when game is ready
317 const move = data.data;
318 if (!!move.cancelDrawOffer) //opponent refuses draw
321 // NOTE for corr games: drawOffer reset by player in turn
322 if (this.game.type == "live" && !!this.game.mycolor)
323 GameStorage.update(this.gameRef.id, {drawOffer: ""});
325 this.$set(this.game, "moveToPlay", move);
329 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
332 this.gameOver("?", "Abort");
335 this.gameOver("1/2", data.data);
338 // NOTE: observers don't know who offered draw
339 this.drawOffer = "received";
343 const chat = data.data;
345 if (!document.getElementById("modalChat").checked)
346 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
351 socketCloseListener: function() {
352 this.conn = new WebSocket(this.connexionString);
353 this.conn.addEventListener('message', this.socketMessageListener);
354 this.conn.addEventListener('close', this.socketCloseListener);
356 // lastate was received, but maybe game wasn't ready yet:
357 processLastate: function() {
358 const data = this.lastate;
359 this.lastate = undefined; //security...
360 const L = this.game.moves.length;
361 if (data.movesCount > L)
363 // Just got last move from him
364 this.$set(this.game, "moveToPlay", Object.assign({initime: data.initime}, data.lastMove));
367 this.drawOffer = "received";
368 if (data.score != "*")
371 if (this.game.score == "*")
372 this.gameOver(data.score);
375 clickDraw: function() {
376 if (!this.game.mycolor)
377 return; //I'm just spectator
378 if (["received","threerep"].includes(this.drawOffer))
380 if (!confirm(this.st.tr["Accept draw?"]))
382 const message = (this.drawOffer == "received"
384 : "Three repetitions");
385 this.send("draw", {data:message});
386 this.gameOver("1/2", message);
388 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
390 if (this.game.mycolor != this.vr.turn)
391 return alert(this.st.tr["Draw offer only in your turn"]);
392 if (!confirm(this.st.tr["Offer draw?"]))
394 this.drawOffer = "sent";
395 this.send("drawoffer");
396 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
399 abortGame: function() {
400 if (!this.game.mycolor || !confirm(this.st.tr["Terminate game?"]))
402 this.gameOver("?", "Abort");
405 resign: function(e) {
406 if (!this.game.mycolor || !confirm(this.st.tr["Resign the game?"]))
408 this.send("resign", {data:this.game.mycolor});
409 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
411 // 3 cases for loading a game:
412 // - from indexedDB (running or completed live game I play)
413 // - from server (one correspondance game I play[ed] or not)
414 // - from remote peer (one live game I don't play, finished or not)
415 loadGame: function(game, callback) {
416 const afterRetrieval = async (game) => {
417 const vModule = await import("@/variants/" + game.vname + ".js");
418 window.V = vModule.VariantRules;
419 this.vr = new V(game.fen);
420 const gtype = (game.cadence.indexOf('d') >= 0 ? "corr" : "live");
421 const tc = extractTime(game.cadence);
424 if (game.players[0].color == "b")
426 // Adopt the same convention for live and corr games: [0] = white
427 [ game.players[0], game.players[1] ] =
428 [ game.players[1], game.players[0] ];
430 // corr game: needs to compute the clocks + initime
431 // NOTE: clocks in seconds, initime in milliseconds
432 game.clocks = [tc.mainTime, tc.mainTime];
433 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
434 if (game.score == "*") //otherwise no need to bother with time
436 game.initime = [0, 0];
437 const L = game.moves.length;
440 let addTime = [0, 0];
441 for (let i=2; i<L; i++)
443 addTime[i%2] += tc.increment -
444 (game.moves[i].played - game.moves[i-1].played) / 1000;
446 for (let i=0; i<=1; i++)
447 game.clocks[i] += addTime[i];
450 game.initime[L%2] = game.moves[L-1].played;
452 // Now that we used idx and played, re-format moves as for live games
453 game.moves = game.moves.map( (m) => {
462 // Also sort chat messages (if any)
463 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
465 const myIdx = game.players.findIndex(p => {
466 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
468 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
470 game.clocks = [tc.mainTime, tc.mainTime];
471 if (game.score == "*")
473 game.initime[0] = Date.now();
476 // I play in this live game; corr games don't have clocks+initime
477 GameStorage.update(game.id,
480 initime: game.initime,
485 if (!!game.drawOffer)
487 if (game.drawOffer == "t") //three repetitions
488 this.drawOffer = "threerep";
492 this.drawOffer = "received"; //by any of the players
495 // I play in this game:
496 if ((game.drawOffer == "w" && myIdx==0) || (game.drawOffer=="b" && myIdx==1))
497 this.drawOffer = "sent";
498 else //all other cases
499 this.drawOffer = "received";
504 game.scoreMsg = this.st.tr[game.scoreMsg]; //stored in english
505 this.game = Object.assign({},
507 // NOTE: assign mycolor here, since BaseGame could also be VS computer
510 increment: tc.increment,
511 mycolor: [undefined,"w","b"][myIdx+1],
512 // opponent sid not strictly required (or available), but easier
513 // at least oppsid or oppid is available anyway:
514 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
515 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
518 this.$nextTick(() => {
519 this.game.rendered = true;
520 // Did lastate arrive before game was rendered?
522 this.processLastate();
524 this.repeat = {}; //reset: scan past moves' FEN:
526 // NOTE: vr_tmp to obtain FEN strings is redundant with BaseGame
527 let vr_tmp = new V(game.fenStart);
528 game.moves.forEach(m => {
530 const fenObj = V.ParseFen( vr_tmp.getFen() );
531 repIdx = fenObj.position + "_" + fenObj.turn;
533 repIdx += "_" + fenObj.flags;
534 this.repeat[repIdx] = (!!this.repeat[repIdx]
535 ? this.repeat[repIdx]+1
538 if (this.repeat[repIdx] >= 3)
539 this.drawOffer = "threerep";
543 return afterRetrieval(game);
544 if (!!this.gameRef.rid)
546 // Remote live game: forgetting about callback func... (TODO: design)
547 this.send("askfullgame", {target:this.gameRef.rid});
551 // Local or corr game
552 GameStorage.get(this.gameRef.id, afterRetrieval);
555 // Post-process a move (which was just played)
556 processMove: function(move) {
557 // Update storage (corr or live) if I play in the game
558 const colorIdx = ["w","b"].indexOf(move.color);
559 const nextIdx = ["w","b"].indexOf(this.vr.turn);
560 // https://stackoverflow.com/a/38750895
561 if (!!this.game.mycolor)
563 const allowed_fields = ["appear", "vanish", "start", "end"];
564 // NOTE: 'var' to see this variable outside this block
565 var filtered_move = Object.keys(move)
566 .filter(key => allowed_fields.includes(key))
567 .reduce((obj, key) => {
568 obj[key] = move[key];
572 // Send move ("newmove" event) to people in the room (if our turn)
574 if (move.color == this.game.mycolor)
576 if (this.drawOffer == "received") //I refuse draw
578 if (this.game.moves.length >= 2) //after first move
580 const elapsed = Date.now() - this.game.initime[colorIdx];
581 // elapsed time is measured in milliseconds
582 addTime = this.game.increment - elapsed/1000;
584 const sendMove = Object.assign({},
588 cancelDrawOffer: this.drawOffer=="",
590 this.send("newmove", {data: sendMove});
591 // (Add)Time indication: useful in case of lastate infos requested
592 move.addTime = addTime;
595 addTime = move.addTime; //supposed transmitted
596 // Update current game object:
597 this.game.moves.push(move);
598 this.game.fen = move.fen;
599 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
600 // move.initime is set only when I receive a "lastate" move from opponent
601 this.game.initime[nextIdx] = move.initime || Date.now();
602 // If repetition detected, consider that a draw offer was received:
603 const fenObj = V.ParseFen(move.fen);
604 let repIdx = fenObj.position + "_" + fenObj.turn;
606 repIdx += "_" + fenObj.flags;
607 this.repeat[repIdx] = (!!this.repeat[repIdx]
608 ? this.repeat[repIdx]+1
610 if (this.repeat[repIdx] >= 3)
611 this.drawOffer = "threerep";
612 else if (this.drawOffer == "threerep")
614 // Since corr games are stored at only one location, update should be
615 // done only by one player for each move:
616 if (!!this.game.mycolor &&
617 (this.game.type == "live" || move.color == this.game.mycolor))
620 switch (this.drawOffer)
626 drawCode = this.game.mycolor;
629 drawCode = this.vr.turn;
632 if (this.game.type == "corr")
634 GameStorage.update(this.gameRef.id,
639 squares: filtered_move,
641 idx: this.game.moves.length - 1,
643 drawOffer: drawCode || "n", //"n" for "None" to force reset (otherwise it's ignored)
648 GameStorage.update(this.gameRef.id,
652 clocks: this.game.clocks,
653 initime: this.game.initime,
659 resetChatColor: function() {
660 // TODO: this is called twice, once on opening an once on closing
661 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
663 processChat: function(chat) {
664 this.send("newchat", {data:chat});
665 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
666 if (this.game.type == "corr" && this.st.user.id > 0)
667 GameStorage.update(this.gameRef.id, {chat: chat});
669 gameOver: function(score, scoreMsg) {
670 this.game.score = score;
671 this.game.scoreMsg = this.st.tr[(!!scoreMsg
673 : getScoreMessage(score))];
674 const myIdx = this.game.players.findIndex(p => {
675 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
677 if (myIdx >= 0) //OK, I play in this game
679 GameStorage.update(this.gameRef.id,
680 {score: score, scoreMsg: scoreMsg});
687 <style lang="sass" scoped>
689 background-color: lightgreen
698 @media screen and (min-width: 768px)
701 @media screen and (max-width: 767px)
706 display: inline-block
709 display: inline-block
712 @media screen and (max-width: 767px)
715 @media screen and (min-width: 768px)
729 display: inline-block
733 display: inline-block
744 .draw-sent, .draw-sent:hover
745 background-color: lightyellow
747 .draw-received, .draw-received:hover
748 background-color: lightgreen
750 .draw-threerep, .draw-threerep:hover
751 background-color: #e4d1fc