3 input#modalChat.modal(type="checkbox" @click="resetChatColor")
4 div#chatWrap(role="dialog" data-checkbox="modalChat"
5 aria-labelledby="inputChat")
7 label.modal-close(for="modalChat")
9 span {{ Object.keys(people).length }} participant(s):
10 span(v-for="p in Object.values(people)" v-if="!!p.name")
12 span.anonymous(v-if="Object.values(people).some(p => !p.name)")
14 Chat(:players="game.players" :pastChats="game.chats"
15 @newchat-sent="finishSendChat" @newchat-received="processChat")
17 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
18 button#chatBtn(onClick="doClick('modalChat')") Chat
19 #actions(v-if="game.score=='*'")
20 button(@click="clickDraw" :class="{['draw-' + drawOffer]: true}") Draw
21 button(@click="abortGame") Abort
22 button(@click="resign") 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", "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("Warning: duplicate 'offline' connection");
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", "Resign");
252 this.gameOver("?", "Abort");
255 this.gameOver("1/2", 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("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", message);
321 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
323 if (!confirm("Offer draw?"))
325 this.drawOffer = "sent";
326 Object.keys(this.people).forEach(sid => {
327 if (sid != this.st.user.sid)
328 this.st.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
330 GameStorage.update(this.gameRef.id, {drawOffer: true});
333 abortGame: function() {
334 if (!confirm(this.st.tr["Terminate game?"]))
336 this.gameOver("?", "Abort");
337 Object.keys(this.people).forEach(sid => {
338 if (sid != this.st.user.sid)
340 this.st.conn.send(JSON.stringify({
347 resign: function(e) {
348 if (!confirm("Resign the game?"))
350 Object.keys(this.people).forEach(sid => {
351 if (sid != this.st.user.sid)
353 this.st.conn.send(JSON.stringify({code:"resign",
354 side:this.game.mycolor, target:sid}));
357 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
359 // 3 cases for loading a game:
360 // - from indexedDB (running or completed live game I play)
361 // - from server (one correspondance game I play[ed] or not)
362 // - from remote peer (one live game I don't play, finished or not)
363 loadGame: function(game, callback) {
364 const afterRetrieval = async (game) => {
365 const vModule = await import("@/variants/" + game.vname + ".js");
366 window.V = vModule.VariantRules;
367 this.vr = new V(game.fen);
368 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
369 const tc = extractTime(game.timeControl);
372 if (game.players[0].color == "b")
374 // Adopt the same convention for live and corr games: [0] = white
375 [ game.players[0], game.players[1] ] =
376 [ game.players[1], game.players[0] ];
378 // corr game: needs to compute the clocks + initime
379 // NOTE: clocks in seconds, initime in milliseconds
380 game.clocks = [tc.mainTime, tc.mainTime];
381 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
382 if (game.score == "*") //otherwise no need to bother with time
384 game.initime = [0, 0];
385 const L = game.moves.length;
388 let addTime = [0, 0];
389 for (let i=2; i<L; i++)
391 addTime[i%2] += tc.increment -
392 (game.moves[i].played - game.moves[i-1].played) / 1000;
394 for (let i=0; i<=1; i++)
395 game.clocks[i] += addTime[i];
398 game.initime[L%2] = game.moves[L-1].played;
400 this.drawOffer = "received";
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,
435 this.game = Object.assign({},
437 // NOTE: assign mycolor here, since BaseGame could also be VS computer
440 increment: tc.increment,
441 mycolor: [undefined,"w","b"][myIdx+1],
442 // opponent sid not strictly required (or available), but easier
443 // at least oppsid or oppid is available anyway:
444 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
445 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
448 this.repeat = {}; //reset
449 if (!!this.lastate) //lastate arrived before game was loaded:
450 this.processLastate();
454 return afterRetrieval(game);
455 if (!!this.gameRef.rid)
457 // Remote live game: forgetting about callback func... (TODO: design)
458 this.st.conn.send(JSON.stringify(
459 {code:"askfullgame", target:this.gameRef.rid}));
463 // Local or corr game
464 GameStorage.get(this.gameRef.id, afterRetrieval);
467 // Post-process a move (which was just played)
468 processMove: function(move) {
469 // Update storage (corr or live) if I play in the game
470 const colorIdx = ["w","b"].indexOf(move.color);
471 // https://stackoverflow.com/a/38750895
472 if (!!this.game.mycolor)
474 const allowed_fields = ["appear", "vanish", "start", "end"];
475 // NOTE: 'var' to see this variable outside this block
476 var filtered_move = Object.keys(move)
477 .filter(key => allowed_fields.includes(key))
478 .reduce((obj, key) => {
479 obj[key] = move[key];
483 // Send move ("newmove" event) to people in the room (if our turn)
485 if (move.color == this.game.mycolor)
487 if (this.game.moves.length >= 2) //after first move
489 const elapsed = Date.now() - this.game.initime[colorIdx];
490 // elapsed time is measured in milliseconds
491 addTime = this.game.increment - elapsed/1000;
493 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
494 Object.keys(this.people).forEach(sid => {
495 if (sid != this.st.user.sid)
497 this.st.conn.send(JSON.stringify({
506 addTime = move.addTime; //supposed transmitted
507 const nextIdx = ["w","b"].indexOf(this.vr.turn);
508 // Since corr games are stored at only one location, update should be
509 // done only by one player for each move:
510 if (!!this.game.mycolor &&
511 (this.game.type == "live" || move.color == this.game.mycolor))
513 if (this.game.type == "corr")
515 GameStorage.update(this.gameRef.id,
520 squares: filtered_move,
521 played: Date.now(), //TODO: on server?
522 idx: this.game.moves.length,
528 GameStorage.update(this.gameRef.id,
532 clocks: this.game.clocks.map((t,i) => i==colorIdx
533 ? this.game.clocks[i] + addTime
534 : this.game.clocks[i]),
535 initime: this.game.initime.map((t,i) => i==nextIdx
537 : this.game.initime[i]),
541 // Also update current game object:
542 this.game.moves.push(move);
543 this.game.fen = move.fen;
544 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
545 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
546 this.game.initime[nextIdx] = Date.now();
547 // If repetition detected, consider that a draw offer was received:
548 const fenObj = V.ParseFen(move.fen);
549 let repIdx = fenObj.position + "_" + fenObj.turn;
551 repIdx += "_" + fenObj.flags;
552 this.repeat[repIdx] = (!!this.repeat[repIdx]
553 ? this.repeat[repIdx]+1
555 if (this.repeat[repIdx] >= 3)
556 this.drawOffer = "threerep";
558 resetChatColor: function() {
559 // TODO: this is called twice, once on opening an once on closing
560 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
562 finishSendChat: function(chat) {
563 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
564 if (this.game.type == "corr" && this.st.user.id > 0)
565 GameStorage.update(this.gameRef.id, {chat: chat});
567 processChat: function() {
568 if (!document.getElementById("modalChat").checked)
569 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
571 gameOver: function(score, scoreMsg) {
572 this.game.score = score;
573 this.game.scoreMsg = scoreMsg;
574 const myIdx = this.game.players.findIndex(p => {
575 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
577 if (myIdx >= 0) //OK, I play in this game
579 GameStorage.update(this.gameRef.id,
580 {score: score, scoreMsg: scoreMsg});
587 <style lang="sass" scoped>
589 background-color: lightgreen
598 @media screen and (min-width: 768px)
601 @media screen and (max-width: 767px)
606 display: inline-block
609 display: inline-block
613 @media screen and (max-width: 767px)
616 @media screen and (min-width: 768px)
626 display: inline-block
630 display: inline-block
641 .draw-sent, .draw-sent:hover
642 background-color: lightyellow
644 .draw-received, .draw-received:hover
645 background-color: lightgreen
647 .draw-threerep, .draw-threerep:hover
648 background-color: #e4d1fc