3 input#modalChat.modal(type="checkbox" @change="toggleChat")
4 div(role="dialog" aria-labelledby="inputChat")
6 label.modal-close(for="modalChat")
7 Chat(:players="game.players" :pastChats="game.chats"
8 @newchat-sent="finishSendChat" @newchat-received="processChat")
10 #aboveBoard.col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
11 button#chatBtn(onClick="doClick('modalChat')") Chat
12 #actions(v-if="game.mode!='analyze' && game.score=='*'")
13 button(@click="offerDraw") Draw
14 button(@click="abortGame") Abort
15 button(@click="resign") Resign
18 span.name(:class="{connected: isConnected(0)}") {{ game.players[0].name }}
19 span.time(v-if="game.score=='*'") {{ virtualClocks[0] }}
21 span.name(:class="{connected: isConnected(1)}") {{ game.players[1].name }}
22 span.time(v-if="game.score=='*'") {{ virtualClocks[1] }}
23 BaseGame(:game="game" :vr="vr" ref="basegame"
24 @newmove="processMove" @gameover="gameOver")
28 import BaseGame from "@/components/BaseGame.vue";
29 import Chat from "@/components/Chat.vue";
30 import { store } from "@/store";
31 import { GameStorage } from "@/utils/gameStorage";
32 import { ppt } from "@/utils/datetime";
33 import { extractTime } from "@/utils/timeControl";
34 import { ArrayFun } from "@/utils/array";
42 // gameRef: to find the game in (potentially remote) storage
46 gameRef: { //given in URL (rid = remote ID)
50 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
51 virtualClocks: [0, 0], //initialized with true game.clocks
52 vr: null, //"variant rules" object initialized from FEN
53 drawOffer: "", //TODO: use for button style
54 people: [], //players + observers
55 lastate: undefined, //used if opponent send lastate before game is ready
56 repeat: {}, //detect position repetition
60 "$route": function(to, from) {
61 this.gameRef.id = to.params["id"];
62 this.gameRef.rid = to.query["rid"];
65 "game.clocks": function(newState) {
66 if (this.game.moves.length < 2 || this.game.score != "*")
68 // 1st move not completed yet, or game over: freeze time
69 this.virtualClocks = newState.map(s => ppt(s));
72 const currentTurn = this.vr.turn;
73 const colorIdx = ["w","b"].indexOf(currentTurn);
74 let countdown = newState[colorIdx] -
75 (Date.now() - this.game.initime[colorIdx])/1000;
76 this.virtualClocks = [0,1].map(i => {
77 const removeTime = i == colorIdx
78 ? (Date.now() - this.game.initime[colorIdx])/1000
80 return ppt(newState[i] - removeTime);
82 let clockUpdate = setInterval(() => {
83 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
85 clearInterval(clockUpdate);
87 this.gameOver(this.vr.turn=="w" ? "0-1" : "1-0", "Time");
91 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
92 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
97 // TODO: redundant code with Hall.vue (related to people array)
99 // Always add myself to players' list
100 const my = this.st.user;
101 this.people.push({sid:my.sid, id:my.id, name:my.name});
102 this.gameRef.id = this.$route.params["id"];
103 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
104 // Define socket .onmessage() and .onclose() events:
105 this.st.conn.onmessage = this.socketMessageListener;
106 const socketCloseListener = () => {
107 store.socketCloseListener(); //reinitialize connexion (in store.js)
108 this.st.conn.addEventListener('message', this.socketMessageListener);
109 this.st.conn.addEventListener('close', socketCloseListener);
111 this.st.conn.onclose = socketCloseListener;
112 // Socket init required before loading remote game:
113 const socketInit = (callback) => {
114 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
116 else //socket not ready yet (initial loading)
117 this.st.conn.onopen = callback;
119 if (!this.gameRef.rid) //game stored locally or on server
120 this.loadGame(null, () => socketInit(this.roomInit));
121 else //game stored remotely: need socket to retrieve it
123 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
124 // --> It will be given when receiving "fullgame" socket event.
125 // A more general approach would be to store it somewhere.
126 socketInit(this.loadGame);
130 // O.1] Ask server for room composition:
131 roomInit: function() {
132 this.st.conn.send(JSON.stringify({code:"pollclients"}));
134 isConnected: function(index) {
135 const name = this.game.players[index].name;
136 if (this.st.user.name == name)
138 return this.people.some(p => p.name == name);
140 socketMessageListener: function(msg) {
141 const data = JSON.parse(msg.data);
145 alert("Warning: duplicate 'offline' connection");
147 // 0.2] Receive clients list (just socket IDs)
150 data.sockIds.forEach(sid => {
151 this.people.push({sid:sid, id:0, name:""});
153 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
159 // Request for identification: reply if I'm not anonymous
160 if (this.st.user.id > 0)
162 this.st.conn.send(JSON.stringify(
163 // people[0] instead of st.user to avoid sending email
164 {code:"identity", user:this.people[0], target:data.from}));
170 let player = this.people.find(p => p.sid == data.user.sid);
171 // NOTE: sometimes player.id fails because player is undefined...
172 // Probably because the event was meant for Hall?
175 player.id = data.user.id;
176 player.name = data.user.name;
177 // Sending last state only for live games: corr games are complete
178 if (this.game.type == "live" && this.game.oppsid == player.sid)
180 // Send our "last state" informations to opponent
181 const L = this.game.moves.length;
182 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
183 if (!!lastMove && this.drawOffer == "sent")
184 lastMove.draw = true;
185 this.st.conn.send(JSON.stringify({
191 score: this.game.score,
193 clocks: this.game.clocks,
200 // Send current (live) game
203 // Minimal game informations:
205 players: this.game.players.map(p => { return {name:p.name}; }),
207 timeControl: this.game.timeControl,
209 this.st.conn.send(JSON.stringify({code:"game",
210 game:myGame, target:data.from}));
213 this.$set(this.game, "moveToPlay", data.move); //TODO: Vue3...
215 case "lastate": //got opponent infos about last move
218 if (!!this.game.type) //game is loaded
219 this.processLastate();
220 //else: will be processed when game is ready
224 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
227 this.gameOver("?", "Abort");
230 this.gameOver("1/2", "Mutual agreement");
233 this.drawOffer = "received"; //TODO: observers don't know who offered draw
236 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
239 // Callback "roomInit" to poll clients only after game is loaded
240 this.loadGame(data.game, this.roomInit);
244 this.people.push({name:"", id:0, sid:data.from});
245 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
249 ArrayFun.remove(this.people, p => p.sid == data.from);
253 // lastate was received, but maybe game wasn't ready yet:
254 processLastate: function() {
255 const data = this.lastate;
256 this.lastate = undefined; //security...
257 const L = this.game.moves.length;
258 if (data.movesCount > L)
260 // Just got last move from him
261 this.$set(this.game, "moveToPlay", data.lastMove);
262 if (data.score != "*" && this.game.score == "*")
264 // Opponent resigned or aborted game, or accepted draw offer
265 // (this is not a stalemate or checkmate)
266 this.gameOver(data.score, "Opponent action");
268 this.game.clocks = data.clocks; //TODO: check this?
269 if (!!data.lastMove.draw)
270 this.drawOffer = "received";
273 offerDraw: function() {
274 if (["received","threerep"].includes(this.drawOffer))
276 if (!confirm("Accept draw?"))
278 this.people.forEach(p => {
279 if (p.sid != this.st.user.sid)
280 this.st.conn.send(JSON.stringify({code:"draw", target:p.sid}));
282 const message = (this.drawOffer == "received"
284 : "Three repetitions");
285 this.gameOver("1/2", message);
287 else if (this.drawOffer == "sent")
290 if (this.game.type == "corr")
291 GameStorage.update(this.gameRef.id, {drawOffer: false});
295 if (!confirm("Offer draw?"))
297 this.drawOffer = "sent";
298 this.people.forEach(p => {
299 if (p.sid != this.st.user.sid)
300 this.st.conn.send(JSON.stringify({code:"drawoffer", target:p.sid}));
302 if (this.game.type == "corr")
303 GameStorage.update(this.gameRef.id, {drawOffer: true});
306 abortGame: function() {
307 if (!confirm(this.st.tr["Terminate game?"]))
309 this.gameOver("?", "Abort");
310 this.people.forEach(p => {
311 if (p.sid != this.st.user.sid)
313 this.st.conn.send(JSON.stringify({
320 resign: function(e) {
321 if (!confirm("Resign the game?"))
323 this.people.forEach(p => {
324 if (p.sid != this.st.user.sid)
326 this.st.conn.send(JSON.stringify({code:"resign",
327 side:this.game.mycolor, target:p.sid}));
330 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
332 // 3 cases for loading a game:
333 // - from indexedDB (running or completed live game I play)
334 // - from server (one correspondance game I play[ed] or not)
335 // - from remote peer (one live game I don't play, finished or not)
336 loadGame: function(game, callback) {
337 const afterRetrieval = async (game) => {
338 const vModule = await import("@/variants/" + game.vname + ".js");
339 window.V = vModule.VariantRules;
340 this.vr = new V(game.fen);
341 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
342 const tc = extractTime(game.timeControl);
345 if (game.players[0].color == "b")
347 // Adopt the same convention for live and corr games: [0] = white
348 [ game.players[0], game.players[1] ] =
349 [ game.players[1], game.players[0] ];
351 // corr game: needs to compute the clocks + initime
352 // NOTE: clocks in seconds, initime in milliseconds
353 game.clocks = [tc.mainTime, tc.mainTime];
354 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
355 if (game.score == "*") //otherwise no need to bother with time
357 game.initime = [0, 0];
358 const L = game.moves.length;
361 let addTime = [0, 0];
362 for (let i=2; i<L; i++)
364 addTime[i%2] += tc.increment -
365 (game.moves[i].played - game.moves[i-1].played) / 1000;
367 for (let i=0; i<=1; i++)
368 game.clocks[i] += addTime[i];
371 game.initime[L%2] = game.moves[L-1].played;
373 this.drawOffer = "received";
375 // Now that we used idx and played, re-format moves as for live games
376 game.moves = game.moves.map( (m) => {
385 // Also sort chat messages (if any)
386 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
388 const myIdx = game.players.findIndex(p => {
389 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
391 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
393 game.clocks = [tc.mainTime, tc.mainTime];
394 if (game.score == "*")
396 game.initime[0] = Date.now();
399 // I play in this live game; corr games don't have clocks+initime
400 GameStorage.update(game.id,
403 initime: game.initime,
408 this.game = Object.assign({},
410 // NOTE: assign mycolor here, since BaseGame could also be VS computer
413 increment: tc.increment,
414 mycolor: [undefined,"w","b"][myIdx+1],
415 // opponent sid not strictly required (or available), but easier
416 // at least oppsid or oppid is available anyway:
417 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
418 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
421 this.repeat = {}; //reset
422 if (!!this.lastate) //lastate arrived before game was loaded:
423 this.processLastate();
427 return afterRetrieval(game);
428 if (!!this.gameRef.rid)
430 // Remote live game: forgetting about callback func... (TODO: design)
431 this.st.conn.send(JSON.stringify(
432 {code:"askfullgame", target:this.gameRef.rid}));
436 // Local or corr game
437 GameStorage.get(this.gameRef.id, afterRetrieval);
440 // Post-process a move (which was just played)
441 processMove: function(move) {
442 // Update storage (corr or live) if I play in the game
443 const colorIdx = ["w","b"].indexOf(move.color);
444 // https://stackoverflow.com/a/38750895
445 if (!!this.game.mycolor)
447 const allowed_fields = ["appear", "vanish", "start", "end"];
448 // NOTE: 'var' to see this variable outside this block
449 var filtered_move = Object.keys(move)
450 .filter(key => allowed_fields.includes(key))
451 .reduce((obj, key) => {
452 obj[key] = move[key];
456 // Send move ("newmove" event) to people in the room (if our turn)
458 if (move.color == this.game.mycolor)
460 if (this.game.moves.length >= 2) //after first move
462 const elapsed = Date.now() - this.game.initime[colorIdx];
463 // elapsed time is measured in milliseconds
464 addTime = this.game.increment - elapsed/1000;
466 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
467 this.people.forEach(p => {
468 if (p.sid != this.st.user.sid)
470 this.st.conn.send(JSON.stringify({
479 addTime = move.addTime; //supposed transmitted
480 const nextIdx = ["w","b"].indexOf(this.vr.turn);
481 // Since corr games are stored at only one location, update should be
482 // done only by one player for each move:
483 if (!!this.game.mycolor &&
484 (this.game.type == "live" || move.color == this.game.mycolor))
486 if (this.game.type == "corr")
488 GameStorage.update(this.gameRef.id,
493 squares: filtered_move,
494 played: Date.now(), //TODO: on server?
495 idx: this.game.moves.length,
501 GameStorage.update(this.gameRef.id,
505 clocks: this.game.clocks.map((t,i) => i==colorIdx
506 ? this.game.clocks[i] + addTime
507 : this.game.clocks[i]),
508 initime: this.game.initime.map((t,i) => i==nextIdx
510 : this.game.initime[i]),
514 // Also update current game object:
515 this.game.moves.push(move);
516 this.game.fen = move.fen;
517 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
518 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
519 this.game.initime[nextIdx] = Date.now();
520 // If repetition detected, consider that a draw offer was received:
521 const fenObj = V.ParseFen(move.fen);
522 let repIdx = fenObj.position + "_" + fenObj.turn;
524 repIdx += "_" + fenObj.flags;
525 this.repeat[repIdx] = (!!this.repeat[repIdx]
526 ? this.repeat[repIdx]+1
528 if (this.repeat[repIdx] >= 3)
529 this.drawOffer = "threerep";
531 toggleChat: function() {
532 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
534 finishSendChat: function(chat) {
535 if (this.game.type == "corr")
536 GameStorage.update(this.gameRef.id, {chat: chat});
538 processChat: function() {
539 if (!document.getElementById("inputChat").checked)
540 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
542 gameOver: function(score, scoreMsg) {
543 this.game.mode = "analyze";
544 this.game.score = score;
545 this.game.scoreMsg = scoreMsg;
546 const myIdx = this.game.players.findIndex(p => {
547 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
549 if (myIdx >= 0) //OK, I play in this game
550 GameStorage.update(this.gameRef.id, { score: score });
558 background-color: lightgreen
560 @media screen and (min-width: 768px)
563 @media screen and (max-width: 767px)
568 display: inline-block
571 display: inline-block
575 @media screen and (max-width: 767px)
585 display: inline-block
589 display: inline-block