3 input#modalChat.modal(type="checkbox" @change="toggleChat")
4 div#chatWrap(role="dialog" data-checkbox="modalChat"
5 aria-labelledby="inputChat")
7 label.modal-close(for="modalChat")
8 Chat(:players="game.players" :pastChats="game.chats"
9 @newchat-sent="finishSendChat" @newchat-received="processChat")
11 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
12 button#chatBtn(onClick="doClick('modalChat')") Chat
13 #actions(v-if="game.score=='*'")
14 button(@click="clickDraw" :class="{['draw-' + drawOffer]: true}") Draw
15 button(@click="abortGame") Abort
16 button(@click="resign") Resign
19 span.name(:class="{connected: isConnected(0)}")
20 | {{ game.players[0].name || "@nonymous" }}
21 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
23 span.name(:class="{connected: isConnected(1)}")
24 | {{ game.players[1].name || "@nonymous" }}
25 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
26 BaseGame(:game="game" :vr="vr" ref="basegame"
27 @newmove="processMove" @gameover="gameOver")
31 import BaseGame from "@/components/BaseGame.vue";
32 import Chat from "@/components/Chat.vue";
33 import { store } from "@/store";
34 import { GameStorage } from "@/utils/gameStorage";
35 import { ppt } from "@/utils/datetime";
36 import { extractTime } from "@/utils/timeControl";
37 import { ArrayFun } from "@/utils/array";
38 import { processModalClick } from "@/utils/modalClick";
46 // gameRef: to find the game in (potentially remote) storage
50 gameRef: { //given in URL (rid = remote ID)
54 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
55 virtualClocks: [0, 0], //initialized with true game.clocks
56 vr: null, //"variant rules" object initialized from FEN
58 people: {}, //players + observers
59 lastate: undefined, //used if opponent send lastate before game is ready
60 repeat: {}, //detect position repetition
64 "$route": function(to, from) {
65 this.gameRef.id = to.params["id"];
66 this.gameRef.rid = to.query["rid"];
69 "game.clocks": function(newState) {
70 if (this.game.moves.length < 2 || this.game.score != "*")
72 // 1st move not completed yet, or game over: freeze time
73 this.virtualClocks = newState.map(s => ppt(s));
76 const currentTurn = this.vr.turn;
77 const colorIdx = ["w","b"].indexOf(currentTurn);
78 let countdown = newState[colorIdx] -
79 (Date.now() - this.game.initime[colorIdx])/1000;
80 this.virtualClocks = [0,1].map(i => {
81 const removeTime = i == colorIdx
82 ? (Date.now() - this.game.initime[colorIdx])/1000
84 return ppt(newState[i] - removeTime);
86 let clockUpdate = setInterval(() => {
87 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
89 clearInterval(clockUpdate);
91 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", "Time");
95 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
96 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
101 // NOTE: some redundant code with Hall.vue (related to people array)
102 created: function() {
103 // Always add myself to players' list
104 const my = this.st.user;
105 this.$set(this.people, my.sid, {id:my.id, name:my.name});
106 this.gameRef.id = this.$route.params["id"];
107 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
108 // Define socket .onmessage() and .onclose() events:
109 this.st.conn.onmessage = this.socketMessageListener;
110 const socketCloseListener = () => {
111 store.socketCloseListener(); //reinitialize connexion (in store.js)
112 this.st.conn.addEventListener('message', this.socketMessageListener);
113 this.st.conn.addEventListener('close', socketCloseListener);
115 this.st.conn.onclose = socketCloseListener;
116 // Socket init required before loading remote game:
117 const socketInit = (callback) => {
118 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
120 else //socket not ready yet (initial loading)
121 this.st.conn.onopen = callback;
123 if (!this.gameRef.rid) //game stored locally or on server
124 this.loadGame(null, () => socketInit(this.roomInit));
125 else //game stored remotely: need socket to retrieve it
127 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
128 // --> It will be given when receiving "fullgame" socket event.
129 // A more general approach would be to store it somewhere.
130 socketInit(this.loadGame);
133 mounted: function() {
134 document.getElementById("chatWrap").addEventListener(
135 "click", processModalClick);
138 // O.1] Ask server for room composition:
139 roomInit: function() {
140 // Notify the room only now that I connected, because
141 // messages might be lost otherwise (if game loading is slow)
142 this.st.conn.send(JSON.stringify({code:"connect"}));
143 this.st.conn.send(JSON.stringify({code:"pollclients"}));
145 isConnected: function(index) {
146 const name = this.game.players[index].name;
147 if (this.st.user.name == name)
149 return Object.values(this.people).some(p => p.name == name);
151 socketMessageListener: function(msg) {
152 const data = JSON.parse(msg.data);
156 alert("Warning: duplicate 'offline' connection");
158 // 0.2] Receive clients list (just socket IDs)
161 data.sockIds.forEach(sid => {
162 // TODO: understand clearly what happens here, problems when a
163 // game is quit, and then launch a new game from hall.
164 if (!!this.people[sid])
166 this.$set(this.people, sid, {id:0, name:""});
168 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
174 // Request for identification: reply if I'm not anonymous
175 if (this.st.user.id > 0)
177 this.st.conn.send(JSON.stringify({code:"identity",
179 // NOTE: decompose to avoid revealing email
180 name: this.st.user.name,
181 sid: this.st.user.sid,
190 // NOTE: sometimes player.id fails because player is undefined...
191 // Probably because the event was meant for Hall?
192 if (!this.people[data.user.sid])
194 this.$set(this.people, data.user.sid,
195 {id: data.user.id, name: data.user.name});
196 // Sending last state only for live games: corr games are complete
197 if (this.game.type == "live" && this.game.oppsid == data.user.sid)
199 // Send our "last state" informations to opponent
200 const L = this.game.moves.length;
201 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
202 if (!!lastMove && this.drawOffer == "sent")
203 lastMove.draw = true;
204 this.st.conn.send(JSON.stringify({
206 target: data.user.sid,
210 score: this.game.score,
212 clocks: this.game.clocks,
219 // Send current (live) game if not asked by opponent (!)
220 if (this.game.players.some(p => p.sid == data.from))
224 // Minimal game informations:
226 players: this.game.players.map(p => { return {name:p.name}; }),
228 timeControl: this.game.timeControl,
230 this.st.conn.send(JSON.stringify({code:"game",
231 game:myGame, target:data.from}));
234 this.$set(this.game, "moveToPlay", data.move);
236 case "lastate": //got opponent infos about last move
239 if (!!this.game.type) //game is loaded
240 this.processLastate();
241 //else: will be processed when game is ready
245 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
248 this.gameOver("?", "Abort");
251 this.gameOver("1/2", data.message);
254 // NOTE: observers don't know who offered draw
255 this.drawOffer = "received";
258 this.st.conn.send(JSON.stringify({code:"fullgame",
259 game:this.game, target:data.from}));
262 // Callback "roomInit" to poll clients only after game is loaded
263 this.loadGame(data.game, this.roomInit);
267 // TODO: next condition is probably not required. See note line 150
268 if (!this.people[data.from])
270 this.$set(this.people, data.from, {name:"", id:0});
271 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
276 this.$delete(this.people, data.from);
280 // lastate was received, but maybe game wasn't ready yet:
281 processLastate: function() {
282 const data = this.lastate;
283 this.lastate = undefined; //security...
284 const L = this.game.moves.length;
285 if (data.movesCount > L)
287 // Just got last move from him
288 this.$set(this.game, "moveToPlay", data.lastMove);
289 if (data.score != "*" && this.game.score == "*")
291 // Opponent resigned or aborted game, or accepted draw offer
292 // (this is not a stalemate or checkmate)
293 this.gameOver(data.score, "Opponent action");
295 this.game.clocks = data.clocks; //TODO: check this?
296 if (!!data.lastMove.draw)
297 this.drawOffer = "received";
300 clickDraw: function() {
301 if (["received","threerep"].includes(this.drawOffer))
303 if (!confirm("Accept draw?"))
305 const message = (this.drawOffer == "received"
307 : "Three repetitions");
308 Object.keys(this.people).forEach(sid => {
309 if (sid != this.st.user.sid)
311 this.st.conn.send(JSON.stringify({code:"draw",
312 message:message, target:sid}));
315 this.gameOver("1/2", message);
317 else if (this.drawOffer == "") //no effect if drawOffer == "sent"
319 if (!confirm("Offer draw?"))
321 this.drawOffer = "sent";
322 Object.keys(this.people).forEach(sid => {
323 if (sid != this.st.user.sid)
324 this.st.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
326 GameStorage.update(this.gameRef.id, {drawOffer: true});
329 abortGame: function() {
330 if (!confirm(this.st.tr["Terminate game?"]))
332 this.gameOver("?", "Abort");
333 Object.keys(this.people).forEach(sid => {
334 if (sid != this.st.user.sid)
336 this.st.conn.send(JSON.stringify({
343 resign: function(e) {
344 if (!confirm("Resign the game?"))
346 Object.keys(this.people).forEach(sid => {
347 if (sid != this.st.user.sid)
349 this.st.conn.send(JSON.stringify({code:"resign",
350 side:this.game.mycolor, target:sid}));
353 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
355 // 3 cases for loading a game:
356 // - from indexedDB (running or completed live game I play)
357 // - from server (one correspondance game I play[ed] or not)
358 // - from remote peer (one live game I don't play, finished or not)
359 loadGame: function(game, callback) {
360 const afterRetrieval = async (game) => {
361 const vModule = await import("@/variants/" + game.vname + ".js");
362 window.V = vModule.VariantRules;
363 this.vr = new V(game.fen);
364 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
365 const tc = extractTime(game.timeControl);
368 if (game.players[0].color == "b")
370 // Adopt the same convention for live and corr games: [0] = white
371 [ game.players[0], game.players[1] ] =
372 [ game.players[1], game.players[0] ];
374 // corr game: needs to compute the clocks + initime
375 // NOTE: clocks in seconds, initime in milliseconds
376 game.clocks = [tc.mainTime, tc.mainTime];
377 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
378 if (game.score == "*") //otherwise no need to bother with time
380 game.initime = [0, 0];
381 const L = game.moves.length;
384 let addTime = [0, 0];
385 for (let i=2; i<L; i++)
387 addTime[i%2] += tc.increment -
388 (game.moves[i].played - game.moves[i-1].played) / 1000;
390 for (let i=0; i<=1; i++)
391 game.clocks[i] += addTime[i];
394 game.initime[L%2] = game.moves[L-1].played;
396 this.drawOffer = "received";
398 // Now that we used idx and played, re-format moves as for live games
399 game.moves = game.moves.map( (m) => {
408 // Also sort chat messages (if any)
409 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
411 const myIdx = game.players.findIndex(p => {
412 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
414 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
416 game.clocks = [tc.mainTime, tc.mainTime];
417 if (game.score == "*")
419 game.initime[0] = Date.now();
422 // I play in this live game; corr games don't have clocks+initime
423 GameStorage.update(game.id,
426 initime: game.initime,
431 this.game = Object.assign({},
433 // NOTE: assign mycolor here, since BaseGame could also be VS computer
436 increment: tc.increment,
437 mycolor: [undefined,"w","b"][myIdx+1],
438 // opponent sid not strictly required (or available), but easier
439 // at least oppsid or oppid is available anyway:
440 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
441 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
444 this.repeat = {}; //reset
445 if (!!this.lastate) //lastate arrived before game was loaded:
446 this.processLastate();
450 return afterRetrieval(game);
451 if (!!this.gameRef.rid)
453 // Remote live game: forgetting about callback func... (TODO: design)
454 this.st.conn.send(JSON.stringify(
455 {code:"askfullgame", target:this.gameRef.rid}));
459 // Local or corr game
460 GameStorage.get(this.gameRef.id, afterRetrieval);
463 // Post-process a move (which was just played)
464 processMove: function(move) {
465 // Update storage (corr or live) if I play in the game
466 const colorIdx = ["w","b"].indexOf(move.color);
467 // https://stackoverflow.com/a/38750895
468 if (!!this.game.mycolor)
470 const allowed_fields = ["appear", "vanish", "start", "end"];
471 // NOTE: 'var' to see this variable outside this block
472 var filtered_move = Object.keys(move)
473 .filter(key => allowed_fields.includes(key))
474 .reduce((obj, key) => {
475 obj[key] = move[key];
479 // Send move ("newmove" event) to people in the room (if our turn)
481 if (move.color == this.game.mycolor)
483 if (this.game.moves.length >= 2) //after first move
485 const elapsed = Date.now() - this.game.initime[colorIdx];
486 // elapsed time is measured in milliseconds
487 addTime = this.game.increment - elapsed/1000;
489 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
490 Object.keys(this.people).forEach(sid => {
491 if (sid != this.st.user.sid)
493 this.st.conn.send(JSON.stringify({
502 addTime = move.addTime; //supposed transmitted
503 const nextIdx = ["w","b"].indexOf(this.vr.turn);
504 // Since corr games are stored at only one location, update should be
505 // done only by one player for each move:
506 if (!!this.game.mycolor &&
507 (this.game.type == "live" || move.color == this.game.mycolor))
509 if (this.game.type == "corr")
511 GameStorage.update(this.gameRef.id,
516 squares: filtered_move,
517 played: Date.now(), //TODO: on server?
518 idx: this.game.moves.length,
524 GameStorage.update(this.gameRef.id,
528 clocks: this.game.clocks.map((t,i) => i==colorIdx
529 ? this.game.clocks[i] + addTime
530 : this.game.clocks[i]),
531 initime: this.game.initime.map((t,i) => i==nextIdx
533 : this.game.initime[i]),
537 // Also update current game object:
538 this.game.moves.push(move);
539 this.game.fen = move.fen;
540 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
541 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
542 this.game.initime[nextIdx] = Date.now();
543 // If repetition detected, consider that a draw offer was received:
544 const fenObj = V.ParseFen(move.fen);
545 let repIdx = fenObj.position + "_" + fenObj.turn;
547 repIdx += "_" + fenObj.flags;
548 this.repeat[repIdx] = (!!this.repeat[repIdx]
549 ? this.repeat[repIdx]+1
551 if (this.repeat[repIdx] >= 3)
552 this.drawOffer = "threerep";
554 toggleChat: function() {
555 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
557 finishSendChat: function(chat) {
558 // NOTE: anonymous chats in corr games are not stored on server (TODO?)
559 if (this.game.type == "corr" && this.st.user.id > 0)
560 GameStorage.update(this.gameRef.id, {chat: chat});
562 processChat: function() {
563 if (!document.getElementById("inputChat").checked)
564 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
566 gameOver: function(score, scoreMsg) {
567 this.game.score = score;
568 this.game.scoreMsg = scoreMsg;
569 const myIdx = this.game.players.findIndex(p => {
570 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
572 if (myIdx >= 0) //OK, I play in this game
574 GameStorage.update(this.gameRef.id,
575 {score: score, scoreMsg: scoreMsg});
582 <style lang="sass" scoped>
584 background-color: lightgreen
586 @media screen and (min-width: 768px)
589 @media screen and (max-width: 767px)
594 display: inline-block
597 display: inline-block
601 @media screen and (max-width: 767px)
611 display: inline-block
615 display: inline-block
626 .draw-sent, .draw-sent:hover
627 background-color: lightyellow
629 .draw-received, .draw-received:hover
630 background-color: lightgreen
632 .draw-threerep, .draw-threerep:hover
633 background-color: #e4d1fc