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.mode!='analyze' && 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)}") {{ game.players[0].name }}
20 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
22 span.name(:class="{connected: isConnected(1)}") {{ game.players[1].name }}
23 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
24 BaseGame(:game="game" :vr="vr" ref="basegame"
25 @newmove="processMove" @gameover="gameOver")
29 import BaseGame from "@/components/BaseGame.vue";
30 import Chat from "@/components/Chat.vue";
31 import { store } from "@/store";
32 import { GameStorage } from "@/utils/gameStorage";
33 import { ppt } from "@/utils/datetime";
34 import { extractTime } from "@/utils/timeControl";
35 import { ArrayFun } from "@/utils/array";
36 import { processModalClick } from "@/utils/modalClick";
44 // gameRef: to find the game in (potentially remote) storage
48 gameRef: { //given in URL (rid = remote ID)
52 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
53 virtualClocks: [0, 0], //initialized with true game.clocks
54 vr: null, //"variant rules" object initialized from FEN
56 people: {}, //players + observers
57 lastate: undefined, //used if opponent send lastate before game is ready
58 repeat: {}, //detect position repetition
62 "$route": function(to, from) {
63 this.gameRef.id = to.params["id"];
64 this.gameRef.rid = to.query["rid"];
67 "game.clocks": function(newState) {
68 if (this.game.moves.length < 2 || this.game.score != "*")
70 // 1st move not completed yet, or game over: freeze time
71 this.virtualClocks = newState.map(s => ppt(s));
74 const currentTurn = this.vr.turn;
75 const colorIdx = ["w","b"].indexOf(currentTurn);
76 let countdown = newState[colorIdx] -
77 (Date.now() - this.game.initime[colorIdx])/1000;
78 this.virtualClocks = [0,1].map(i => {
79 const removeTime = i == colorIdx
80 ? (Date.now() - this.game.initime[colorIdx])/1000
82 return ppt(newState[i] - removeTime);
84 let clockUpdate = setInterval(() => {
85 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
87 clearInterval(clockUpdate);
89 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", "Time");
93 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
94 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
99 // NOTE: some redundant code with Hall.vue (related to people array)
100 created: function() {
101 // Always add myself to players' list
102 const my = this.st.user;
103 this.$set(this.people, my.sid, {id:my.id, name:my.name});
104 this.gameRef.id = this.$route.params["id"];
105 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
106 // Define socket .onmessage() and .onclose() events:
107 this.st.conn.onmessage = this.socketMessageListener;
108 const socketCloseListener = () => {
109 store.socketCloseListener(); //reinitialize connexion (in store.js)
110 this.st.conn.addEventListener('message', this.socketMessageListener);
111 this.st.conn.addEventListener('close', socketCloseListener);
113 this.st.conn.onclose = socketCloseListener;
114 // Socket init required before loading remote game:
115 const socketInit = (callback) => {
116 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
118 else //socket not ready yet (initial loading)
119 this.st.conn.onopen = callback;
121 if (!this.gameRef.rid) //game stored locally or on server
122 this.loadGame(null, () => socketInit(this.roomInit));
123 else //game stored remotely: need socket to retrieve it
125 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
126 // --> It will be given when receiving "fullgame" socket event.
127 // A more general approach would be to store it somewhere.
128 socketInit(this.loadGame);
131 mounted: function() {
132 document.getElementById("chatWrap").addEventListener(
133 "click", processModalClick);
136 // O.1] Ask server for room composition:
137 roomInit: function() {
138 this.st.conn.send(JSON.stringify({code:"pollclients"}));
140 isConnected: function(index) {
141 const name = this.game.players[index].name;
142 if (this.st.user.name == name)
144 return Object.values(this.people).some(p => p.name == name);
146 socketMessageListener: function(msg) {
147 const data = JSON.parse(msg.data);
151 alert("Warning: duplicate 'offline' connection");
153 // 0.2] Receive clients list (just socket IDs)
156 data.sockIds.forEach(sid => {
157 // TODO: understand clearly what happens here, problems when a
158 // game is quit, and then launch a new game from hall.
159 if (!!this.people[sid])
161 this.$set(this.people, sid, {id:0, name:""});
163 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
169 // Request for identification: reply if I'm not anonymous
170 if (this.st.user.id > 0)
172 this.st.conn.send(JSON.stringify({code:"identity",
174 // NOTE: decompose to avoid revealing email
175 name: this.st.user.name,
176 sid: this.st.user.sid,
185 let player = this.people[data.user.sid];
186 // NOTE: sometimes player.id fails because player is undefined...
187 // Probably because the event was meant for Hall?
190 player.id = data.user.id;
191 player.name = data.user.name;
192 // Sending last state only for live games: corr games are complete
193 if (this.game.type == "live" && this.game.oppsid == data.user.sid)
195 // Send our "last state" informations to opponent
196 const L = this.game.moves.length;
197 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
198 if (!!lastMove && this.drawOffer == "sent")
199 lastMove.draw = true;
200 this.st.conn.send(JSON.stringify({
202 target: data.user.sid,
206 score: this.game.score,
208 clocks: this.game.clocks,
215 // Send current (live) game
218 // Minimal game informations:
220 players: this.game.players.map(p => { return {name:p.name}; }),
222 timeControl: this.game.timeControl,
224 this.st.conn.send(JSON.stringify({code:"game",
225 game:myGame, target:data.from}));
228 this.$set(this.game, "moveToPlay", data.move); //TODO: Vue3...
230 case "lastate": //got opponent infos about last move
233 if (!!this.game.type) //game is loaded
234 this.processLastate();
235 //else: will be processed when game is ready
239 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
242 this.gameOver("?", "Abort");
245 this.gameOver("1/2", data.message);
248 this.drawOffer = "received"; //TODO: observers don't know who offered draw
251 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
254 // Callback "roomInit" to poll clients only after game is loaded
255 this.loadGame(data.game, this.roomInit);
259 // TODO: next condition is probably not required. See note line 150
260 if (!this.people[data.from])
262 this.$set(this.people, data.from, {name:"", id:0});
263 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
268 this.$delete(this.people, data.from);
272 // lastate was received, but maybe game wasn't ready yet:
273 processLastate: function() {
274 const data = this.lastate;
275 this.lastate = undefined; //security...
276 const L = this.game.moves.length;
277 if (data.movesCount > L)
279 // Just got last move from him
280 this.$set(this.game, "moveToPlay", data.lastMove);
281 if (data.score != "*" && this.game.score == "*")
283 // Opponent resigned or aborted game, or accepted draw offer
284 // (this is not a stalemate or checkmate)
285 this.gameOver(data.score, "Opponent action");
287 this.game.clocks = data.clocks; //TODO: check this?
288 if (!!data.lastMove.draw)
289 this.drawOffer = "received";
292 clickDraw: function() {
293 if (["received","threerep"].includes(this.drawOffer))
295 if (!confirm("Accept draw?"))
297 const message = (this.drawOffer == "received"
299 : "Three repetitions");
300 Object.keys(this.people).forEach(sid => {
301 if (sid != this.st.user.sid)
303 this.st.conn.send(JSON.stringify({code:"draw",
304 message:message, target:sid}));
307 this.gameOver("1/2", message);
309 else if (this.drawOffer == "sent")
312 if (this.game.type == "corr")
313 GameStorage.update(this.gameRef.id, {drawOffer: false});
317 if (!confirm("Offer draw?"))
319 this.drawOffer = "sent";
320 Object.keys(this.people).forEach(sid => {
321 if (sid != this.st.user.sid)
322 this.st.conn.send(JSON.stringify({code:"drawoffer", target:sid}));
324 if (this.game.type == "corr")
325 GameStorage.update(this.gameRef.id, {drawOffer: true});
328 abortGame: function() {
329 if (!confirm(this.st.tr["Terminate game?"]))
331 this.gameOver("?", "Abort");
332 Object.keys(this.people).forEach(sid => {
333 if (sid != this.st.user.sid)
335 this.st.conn.send(JSON.stringify({
342 resign: function(e) {
343 if (!confirm("Resign the game?"))
345 Object.keys(this.people).forEach(sid => {
346 if (sid != this.st.user.sid)
348 this.st.conn.send(JSON.stringify({code:"resign",
349 side:this.game.mycolor, target:sid}));
352 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
354 // 3 cases for loading a game:
355 // - from indexedDB (running or completed live game I play)
356 // - from server (one correspondance game I play[ed] or not)
357 // - from remote peer (one live game I don't play, finished or not)
358 loadGame: function(game, callback) {
359 const afterRetrieval = async (game) => {
360 const vModule = await import("@/variants/" + game.vname + ".js");
361 window.V = vModule.VariantRules;
362 this.vr = new V(game.fen);
363 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
364 const tc = extractTime(game.timeControl);
367 if (game.players[0].color == "b")
369 // Adopt the same convention for live and corr games: [0] = white
370 [ game.players[0], game.players[1] ] =
371 [ game.players[1], game.players[0] ];
373 // corr game: needs to compute the clocks + initime
374 // NOTE: clocks in seconds, initime in milliseconds
375 game.clocks = [tc.mainTime, tc.mainTime];
376 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
377 if (game.score == "*") //otherwise no need to bother with time
379 game.initime = [0, 0];
380 const L = game.moves.length;
383 let addTime = [0, 0];
384 for (let i=2; i<L; i++)
386 addTime[i%2] += tc.increment -
387 (game.moves[i].played - game.moves[i-1].played) / 1000;
389 for (let i=0; i<=1; i++)
390 game.clocks[i] += addTime[i];
393 game.initime[L%2] = game.moves[L-1].played;
395 this.drawOffer = "received";
397 // Now that we used idx and played, re-format moves as for live games
398 game.moves = game.moves.map( (m) => {
407 // Also sort chat messages (if any)
408 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
410 const myIdx = game.players.findIndex(p => {
411 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
413 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
415 game.clocks = [tc.mainTime, tc.mainTime];
416 if (game.score == "*")
418 game.initime[0] = Date.now();
421 // I play in this live game; corr games don't have clocks+initime
422 GameStorage.update(game.id,
425 initime: game.initime,
430 this.game = Object.assign({},
432 // NOTE: assign mycolor here, since BaseGame could also be VS computer
435 increment: tc.increment,
436 mycolor: [undefined,"w","b"][myIdx+1],
437 // opponent sid not strictly required (or available), but easier
438 // at least oppsid or oppid is available anyway:
439 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
440 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
443 this.repeat = {}; //reset
444 if (!!this.lastate) //lastate arrived before game was loaded:
445 this.processLastate();
449 return afterRetrieval(game);
450 if (!!this.gameRef.rid)
452 // Remote live game: forgetting about callback func... (TODO: design)
453 this.st.conn.send(JSON.stringify(
454 {code:"askfullgame", target:this.gameRef.rid}));
458 // Local or corr game
459 GameStorage.get(this.gameRef.id, afterRetrieval);
462 // Post-process a move (which was just played)
463 processMove: function(move) {
464 // Update storage (corr or live) if I play in the game
465 const colorIdx = ["w","b"].indexOf(move.color);
466 // https://stackoverflow.com/a/38750895
467 if (!!this.game.mycolor)
469 const allowed_fields = ["appear", "vanish", "start", "end"];
470 // NOTE: 'var' to see this variable outside this block
471 var filtered_move = Object.keys(move)
472 .filter(key => allowed_fields.includes(key))
473 .reduce((obj, key) => {
474 obj[key] = move[key];
478 // Send move ("newmove" event) to people in the room (if our turn)
480 if (move.color == this.game.mycolor)
482 if (this.game.moves.length >= 2) //after first move
484 const elapsed = Date.now() - this.game.initime[colorIdx];
485 // elapsed time is measured in milliseconds
486 addTime = this.game.increment - elapsed/1000;
488 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
489 Object.keys(this.people).forEach(sid => {
490 if (sid != this.st.user.sid)
492 this.st.conn.send(JSON.stringify({
501 addTime = move.addTime; //supposed transmitted
502 const nextIdx = ["w","b"].indexOf(this.vr.turn);
503 // Since corr games are stored at only one location, update should be
504 // done only by one player for each move:
505 if (!!this.game.mycolor &&
506 (this.game.type == "live" || move.color == this.game.mycolor))
508 if (this.game.type == "corr")
510 GameStorage.update(this.gameRef.id,
515 squares: filtered_move,
516 played: Date.now(), //TODO: on server?
517 idx: this.game.moves.length,
523 GameStorage.update(this.gameRef.id,
527 clocks: this.game.clocks.map((t,i) => i==colorIdx
528 ? this.game.clocks[i] + addTime
529 : this.game.clocks[i]),
530 initime: this.game.initime.map((t,i) => i==nextIdx
532 : this.game.initime[i]),
536 // Also update current game object:
537 this.game.moves.push(move);
538 this.game.fen = move.fen;
539 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
540 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
541 this.game.initime[nextIdx] = Date.now();
542 // If repetition detected, consider that a draw offer was received:
543 const fenObj = V.ParseFen(move.fen);
544 let repIdx = fenObj.position + "_" + fenObj.turn;
546 repIdx += "_" + fenObj.flags;
547 this.repeat[repIdx] = (!!this.repeat[repIdx]
548 ? this.repeat[repIdx]+1
550 if (this.repeat[repIdx] >= 3)
551 this.drawOffer = "threerep";
553 toggleChat: function() {
554 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
556 finishSendChat: function(chat) {
557 if (this.game.type == "corr")
558 GameStorage.update(this.gameRef.id, {chat: chat});
560 processChat: function() {
561 if (!document.getElementById("inputChat").checked)
562 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
564 gameOver: function(score, scoreMsg) {
565 this.game.mode = "analyze";
566 this.game.score = score;
567 this.game.scoreMsg = scoreMsg;
568 const myIdx = this.game.players.findIndex(p => {
569 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
571 if (myIdx >= 0) //OK, I play in this game
573 GameStorage.update(this.gameRef.id,
574 {score: score, scoreMsg: scoreMsg});
583 background-color: lightgreen
585 @media screen and (min-width: 768px)
588 @media screen and (max-width: 767px)
593 display: inline-block
596 display: inline-block
600 @media screen and (max-width: 767px)
610 display: inline-block
614 display: inline-block
625 .draw-sent, .draw-sent:hover
626 background-color: lightyellow
628 .draw-received, .draw-received:hover
629 background-color: lightgreen
631 .draw-threerep, .draw-threerep:hover
632 background-color: #e4d1fc