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-sent="finishSendChat" @newchat-received="processChat")
16 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
17 button#chatBtn(onClick="doClick('modalChat')") Chat
18 #actions(v-if="game.score=='*'")
19 button(@click="clickDraw" :class="{['draw-' + drawOffer]: true}")
21 button(@click="abortGame") {{ st.tr["Abort"] }}
22 button(@click="resign") {{ st.tr["Resign"] }}
25 span.name(:class="{connected: isConnected(0)}")
26 | {{ game.players[0].name || "@nonymous" }}
27 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
29 span.name(:class="{connected: isConnected(1)}")
30 | {{ game.players[1].name || "@nonymous" }}
31 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
32 BaseGame(:game="game" :vr="vr" ref="basegame"
33 @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 { ArrayFun } from "@/utils/array";
44 import { processModalClick } from "@/utils/modalClick";
52 // gameRef: to find the game in (potentially remote) storage
56 gameRef: { //given in URL (rid = remote ID)
60 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
61 virtualClocks: [0, 0], //initialized with true game.clocks
62 vr: null, //"variant rules" object initialized from FEN
64 people: {}, //players + observers
65 lastate: undefined, //used if opponent send lastate before game is ready
66 repeat: {}, //detect position repetition
70 "$route": function(to, from) {
71 this.gameRef.id = to.params["id"];
72 this.gameRef.rid = to.query["rid"];
75 "game.clocks": function(newState) {
76 if (this.game.moves.length < 2 || this.game.score != "*")
78 // 1st move not completed yet, or game over: freeze time
79 this.virtualClocks = newState.map(s => ppt(s));
82 const currentTurn = this.vr.turn;
83 const colorIdx = ["w","b"].indexOf(currentTurn);
84 let countdown = newState[colorIdx] -
85 (Date.now() - this.game.initime[colorIdx])/1000;
86 this.virtualClocks = [0,1].map(i => {
87 const removeTime = i == colorIdx
88 ? (Date.now() - this.game.initime[colorIdx])/1000
90 return ppt(newState[i] - removeTime);
92 let clockUpdate = setInterval(() => {
93 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
95 clearInterval(clockUpdate);
97 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", this.st.tr["Time"]);
101 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
102 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 if (this.game.type == "live" && this.game.oppsid == data.user.sid)
203 // Send our "last state" informations to opponent
204 const L = this.game.moves.length;
205 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
206 if (!!lastMove && this.drawOffer == "sent")
207 lastMove.draw = true;
208 this.st.conn.send(JSON.stringify({
210 target: data.user.sid,
214 score: this.game.score,
216 clocks: this.game.clocks,
223 // Send current (live) game if not asked by opponent (!)
224 if (this.game.players.some(p => p.sid == data.from))
228 // Minimal game informations:
230 players: this.game.players,
232 timeControl: this.game.timeControl,
234 this.st.conn.send(JSON.stringify({code:"game",
235 game:myGame, target:data.from}));
238 this.$set(this.game, "moveToPlay", data.move);
240 case "lastate": //got opponent infos about last move
243 if (!!this.game.type) //game is loaded
244 this.processLastate();
245 //else: will be processed when game is ready
249 this.gameOver(data.side=="b" ? "1-0" : "0-1", this.st.tr["Resign"]);
252 this.gameOver("?", this.st.tr["Abort"]);
255 this.gameOver("1/2", this.st.tr[data.message]);
258 // NOTE: observers don't know who offered draw
259 this.drawOffer = "received";
262 this.st.conn.send(JSON.stringify({code:"fullgame",
263 game:this.game, target:data.from}));
266 // Callback "roomInit" to poll clients only after game is loaded
267 this.loadGame(data.game, this.roomInit);
271 // TODO: next condition is probably not required. See note line 150
272 if (!this.people[data.from])
274 this.$set(this.people, data.from, {name:"", id:0});
275 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
280 this.$delete(this.people, data.from);
284 // lastate was received, but maybe game wasn't ready yet:
285 processLastate: function() {
286 const data = this.lastate;
287 this.lastate = undefined; //security...
288 const L = this.game.moves.length;
289 if (data.movesCount > L)
291 // Just got last move from him
292 this.$set(this.game, "moveToPlay", data.lastMove);
293 if (data.score != "*" && this.game.score == "*")
295 // Opponent resigned or aborted game, or accepted draw offer
296 // (this is not a stalemate or checkmate)
297 this.gameOver(data.score, "Opponent action");
299 this.game.clocks = data.clocks; //TODO: check this?
300 if (!!data.lastMove.draw)
301 this.drawOffer = "received";
304 clickDraw: function() {
305 if (["received","threerep"].includes(this.drawOffer))
307 if (!confirm(this.st.tr["Accept draw?"]))
309 const message = (this.drawOffer == "received"
311 : "Three repetitions");
312 Object.keys(this.people).forEach(sid => {
313 if (sid != this.st.user.sid)
315 this.st.conn.send(JSON.stringify({code:"draw",
316 message:message, target:sid}));
319 this.gameOver("1/2", this.st.tr[message]);
321 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
323 if (this.game.mycolor != this.vr.turn)
324 return alert(this.st.tr["Draw offer only in your turn"]);
325 if (!confirm(this.st.tr["Offer draw?"]))
327 this.drawOffer = "sent";
328 Object.keys(this.people).forEach(sid => {
329 if (sid != this.st.user.sid)
330 this.st.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
332 GameStorage.update(this.gameRef.id, {drawOffer: this.game.mycolor});
335 abortGame: function() {
336 if (!confirm(this.st.tr["Terminate game?"]))
338 this.gameOver("?", this.st.tr["Abort"]);
339 Object.keys(this.people).forEach(sid => {
340 if (sid != this.st.user.sid)
342 this.st.conn.send(JSON.stringify({
349 resign: function(e) {
350 if (!confirm(this.st.tr["Resign the game?"]))
352 Object.keys(this.people).forEach(sid => {
353 if (sid != this.st.user.sid)
355 this.st.conn.send(JSON.stringify({code:"resign",
356 side:this.game.mycolor, target:sid}));
359 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", this.st.tr["Resign"]);
361 // 3 cases for loading a game:
362 // - from indexedDB (running or completed live game I play)
363 // - from server (one correspondance game I play[ed] or not)
364 // - from remote peer (one live game I don't play, finished or not)
365 loadGame: function(game, callback) {
366 const afterRetrieval = async (game) => {
367 const vModule = await import("@/variants/" + game.vname + ".js");
368 window.V = vModule.VariantRules;
369 this.vr = new V(game.fen);
370 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
371 const tc = extractTime(game.timeControl);
374 if (game.players[0].color == "b")
376 // Adopt the same convention for live and corr games: [0] = white
377 [ game.players[0], game.players[1] ] =
378 [ game.players[1], game.players[0] ];
380 // corr game: needs to compute the clocks + initime
381 // NOTE: clocks in seconds, initime in milliseconds
382 game.clocks = [tc.mainTime, tc.mainTime];
383 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
384 if (game.score == "*") //otherwise no need to bother with time
386 game.initime = [0, 0];
387 const L = game.moves.length;
390 let addTime = [0, 0];
391 for (let i=2; i<L; i++)
393 addTime[i%2] += tc.increment -
394 (game.moves[i].played - game.moves[i-1].played) / 1000;
396 for (let i=0; i<=1; i++)
397 game.clocks[i] += addTime[i];
400 game.initime[L%2] = game.moves[L-1].played;
402 // Now that we used idx and played, re-format moves as for live games
403 game.moves = game.moves.map( (m) => {
412 // Also sort chat messages (if any)
413 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
415 const myIdx = game.players.findIndex(p => {
416 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
418 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
420 game.clocks = [tc.mainTime, tc.mainTime];
421 if (game.score == "*")
423 game.initime[0] = Date.now();
426 // I play in this live game; corr games don't have clocks+initime
427 GameStorage.update(game.id,
430 initime: game.initime,
438 // TODO: (and also when receiving / sending a move ?)
439 // if (!!game.drawOffer)
441 // if (game.drawOffer == "w")
445 // this.drawOffer = "sent";
451 this.game = Object.assign({},
453 // NOTE: assign mycolor here, since BaseGame could also be VS computer
456 increment: tc.increment,
457 mycolor: [undefined,"w","b"][myIdx+1],
458 // opponent sid not strictly required (or available), but easier
459 // at least oppsid or oppid is available anyway:
460 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
461 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
464 this.repeat = {}; //reset
465 if (!!this.lastate) //lastate arrived before game was loaded:
466 this.processLastate();
470 return afterRetrieval(game);
471 if (!!this.gameRef.rid)
473 // Remote live game: forgetting about callback func... (TODO: design)
474 this.st.conn.send(JSON.stringify(
475 {code:"askfullgame", target:this.gameRef.rid}));
479 // Local or corr game
480 GameStorage.get(this.gameRef.id, afterRetrieval);
483 // Post-process a move (which was just played)
484 processMove: function(move) {
485 // Update storage (corr or live) if I play in the game
486 const colorIdx = ["w","b"].indexOf(move.color);
487 // https://stackoverflow.com/a/38750895
488 if (!!this.game.mycolor)
490 const allowed_fields = ["appear", "vanish", "start", "end"];
491 // NOTE: 'var' to see this variable outside this block
492 var filtered_move = Object.keys(move)
493 .filter(key => allowed_fields.includes(key))
494 .reduce((obj, key) => {
495 obj[key] = move[key];
499 // Send move ("newmove" event) to people in the room (if our turn)
501 if (move.color == this.game.mycolor)
503 if (this.game.moves.length >= 2) //after first move
505 const elapsed = Date.now() - this.game.initime[colorIdx];
506 // elapsed time is measured in milliseconds
507 addTime = this.game.increment - elapsed/1000;
509 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
510 Object.keys(this.people).forEach(sid => {
511 if (sid != this.st.user.sid)
513 this.st.conn.send(JSON.stringify({
522 addTime = move.addTime; //supposed transmitted
523 const nextIdx = ["w","b"].indexOf(this.vr.turn);
524 // Since corr games are stored at only one location, update should be
525 // done only by one player for each move:
526 if (!!this.game.mycolor &&
527 (this.game.type == "live" || move.color == this.game.mycolor))
529 if (this.game.type == "corr")
531 GameStorage.update(this.gameRef.id,
536 squares: filtered_move,
537 played: Date.now(), //TODO: on server?
538 idx: this.game.moves.length,
544 GameStorage.update(this.gameRef.id,
548 clocks: this.game.clocks.map((t,i) => i==colorIdx
549 ? this.game.clocks[i] + addTime
550 : this.game.clocks[i]),
551 initime: this.game.initime.map((t,i) => i==nextIdx
553 : this.game.initime[i]),
557 // Also update current game object:
558 this.game.moves.push(move);
559 this.game.fen = move.fen;
560 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
561 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
562 this.game.initime[nextIdx] = Date.now();
563 // If repetition detected, consider that a draw offer was received:
564 const fenObj = V.ParseFen(move.fen);
565 let repIdx = fenObj.position + "_" + fenObj.turn;
567 repIdx += "_" + fenObj.flags;
568 this.repeat[repIdx] = (!!this.repeat[repIdx]
569 ? this.repeat[repIdx]+1
571 if (this.repeat[repIdx] >= 3)
572 this.drawOffer = "threerep";
574 resetChatColor: function() {
575 // TODO: this is called twice, once on opening an once on closing
576 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
578 finishSendChat: function(chat) {
579 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
580 if (this.game.type == "corr" && this.st.user.id > 0)
581 GameStorage.update(this.gameRef.id, {chat: chat});
583 processChat: function() {
584 if (!document.getElementById("modalChat").checked)
585 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
587 gameOver: function(score, scoreMsg) {
588 this.game.score = score;
589 this.game.scoreMsg = scoreMsg;
590 const myIdx = this.game.players.findIndex(p => {
591 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
593 if (myIdx >= 0) //OK, I play in this game
595 GameStorage.update(this.gameRef.id,
596 {score: score, scoreMsg: scoreMsg});
603 <style lang="sass" scoped>
605 background-color: lightgreen
614 @media screen and (min-width: 768px)
617 @media screen and (max-width: 767px)
622 display: inline-block
625 display: inline-block
629 @media screen and (max-width: 767px)
632 @media screen and (min-width: 768px)
642 display: inline-block
646 display: inline-block
657 .draw-sent, .draw-sent:hover
658 background-color: lightyellow
660 .draw-received, .draw-received:hover
661 background-color: lightgreen
663 .draw-threerep, .draw-threerep:hover
664 background-color: #e4d1fc