3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
4 BaseGame(:game="game" :vr="vr" ref="basegame"
5 @newmove="processMove" @gameover="gameOver")
6 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
7 div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
8 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
9 button(@click="offerDraw") Draw
10 button(@click="abortGame") Abort
11 button(@click="resign") Resign
12 textarea(v-if="game.score=='*'" v-model="corrMsg")
13 Chat(:players="game.players")
17 import BaseGame from "@/components/BaseGame.vue";
18 import Chat from "@/components/Chat.vue";
19 import { store } from "@/store";
20 import { GameStorage } from "@/utils/gameStorage";
21 import { ppt } from "@/utils/datetime";
22 import { extractTime } from "@/utils/timeControl";
23 import { ArrayFun } from "@/utils/array";
31 // gameRef: to find the game in (potentially remote) storage
35 gameRef: { //given in URL (rid = remote ID)
39 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
40 corrMsg: "", //to send offline messages in corr games
41 virtualClocks: [0, 0], //initialized with true game.clocks
42 vr: null, //"variant rules" object initialized from FEN
43 drawOffer: "", //TODO: use for button style
44 people: [], //players + observers
45 lastate: undefined, //used if opponent send lastate before game is ready
49 "$route": function(to, from) {
50 this.gameRef.id = to.params["id"];
51 this.gameRef.rid = to.query["rid"];
54 "game.clocks": function(newState) {
55 if (this.game.moves.length < 2 || this.game.score != "*")
57 // 1st move not completed yet, or game over: freeze time
58 this.virtualClocks = newState.map(s => ppt(s));
61 const currentTurn = this.vr.turn;
62 const colorIdx = ["w","b"].indexOf(currentTurn);
63 let countdown = newState[colorIdx] -
64 (Date.now() - this.game.initime[colorIdx])/1000;
65 this.virtualClocks = [0,1].map(i => {
66 const removeTime = i == colorIdx
67 ? (Date.now() - this.game.initime[colorIdx])/1000
69 return ppt(newState[i] - removeTime);
71 let clockUpdate = setInterval(() => {
72 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
74 clearInterval(clockUpdate);
77 this.$refs["basegame"].endGame(
78 this.vr.turn=="w" ? "0-1" : "1-0", "Time");
83 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
84 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
89 // TODO: redundant code with Hall.vue (related to people array)
91 // Always add myself to players' list
92 const my = this.st.user;
93 this.people.push({sid:my.sid, id:my.id, name:my.name});
94 this.gameRef.id = this.$route.params["id"];
95 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
96 // Define socket .onmessage() and .onclose() events:
97 this.st.conn.onmessage = this.socketMessageListener;
98 const socketCloseListener = () => {
99 store.socketCloseListener(); //reinitialize connexion (in store.js)
100 this.st.conn.addEventListener('message', this.socketMessageListener);
101 this.st.conn.addEventListener('close', socketCloseListener);
103 this.st.conn.onclose = socketCloseListener;
104 // Socket init required before loading remote game:
105 const socketInit = (callback) => {
106 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
108 else //socket not ready yet (initial loading)
109 this.st.conn.onopen = callback;
111 if (!this.gameRef.rid) //game stored locally or on server
112 this.loadGame(null, () => socketInit(this.roomInit));
113 else //game stored remotely: need socket to retrieve it
115 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
116 // --> It will be given when receiving "fullgame" socket event.
117 // A more general approach would be to store it somewhere.
118 socketInit(this.loadGame);
122 // O.1] Ask server for room composition:
123 roomInit: function() {
124 this.st.conn.send(JSON.stringify({code:"pollclients"}));
126 socketMessageListener: function(msg) {
127 const data = JSON.parse(msg.data);
131 alert("Warning: duplicate 'offline' connection");
133 // 0.2] Receive clients list (just socket IDs)
136 data.sockIds.forEach(sid => {
137 this.people.push({sid:sid, id:0, name:""});
139 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
145 // Request for identification: reply if I'm not anonymous
146 if (this.st.user.id > 0)
148 this.st.conn.send(JSON.stringify(
149 // people[0] instead of st.user to avoid sending email
150 {code:"identity", user:this.people[0], target:data.from}));
156 let player = this.people.find(p => p.sid == data.user.sid);
157 // NOTE: sometimes player.id fails because player is undefined...
158 // Probably because the event was meant for Hall?
161 player.id = data.user.id;
162 player.name = data.user.name;
163 // Sending last state only for live games: corr games are complete
164 if (this.game.type == "live" && this.game.oppsid == player.sid)
166 // Send our "last state" informations to opponent
167 const L = this.game.moves.length;
168 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
169 if (!!lastMove && this.drawOffer == "sent")
170 lastMove.draw = true;
171 this.st.conn.send(JSON.stringify({
177 score: this.game.score,
179 clocks: this.game.clocks,
186 // Send current (live) game
189 // Minimal game informations:
191 players: this.game.players.map(p => { return {name:p.name}; }),
193 timeControl: this.game.timeControl,
195 this.st.conn.send(JSON.stringify({code:"game",
196 game:myGame, target:data.from}));
199 // NOTE: this call to play() will trigger processMove()
200 this.$refs["basegame"].play(data.move,
201 "receive", this.game.vname!="Dark" ? "animate" : null);
203 case "lastate": //got opponent infos about last move
206 if (!!this.game.type) //game is loaded
207 this.processLastate();
208 //else: will be processed when game is ready
212 this.$refs["basegame"].endGame(
213 (data.side=="b" ? "1-0" : "0-1"), "Resign");
216 this.$refs["basegame"].endGame("?", "Abort");
219 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
222 this.drawOffer = "received"; //TODO: observers don't know who offered draw
225 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
228 // Callback "roomInit" to poll clients only after game is loaded
229 this.loadGame(data.game, this.roomInit);
233 this.people.push({name:"", id:0, sid:data.from});
234 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
238 ArrayFun.remove(this.people, p => p.sid == data.from);
242 // lastate was received, but maybe game wasn't ready yet:
243 processLastate: function() {
244 const data = this.lastate;
245 this.lastate = undefined; //security...
246 const L = this.game.moves.length;
247 if (data.movesCount > L)
249 // Just got last move from him
250 this.$refs["basegame"].play(data.lastMove,
251 "receive", this.game.vname!="Dark" ? "animate" : null);
252 if (data.score != "*" && this.game.score == "*")
254 // Opponent resigned or aborted game, or accepted draw offer
255 // (this is not a stalemate or checkmate)
256 this.$refs["basegame"].endGame(data.score, "Opponent action");
258 this.game.clocks = data.clocks; //TODO: check this?
259 if (!!data.lastMove.draw)
260 this.drawOffer = "received";
263 offerDraw: function() {
264 if (this.drawOffer == "received")
266 if (!confirm("Accept draw?"))
268 this.people.forEach(p => {
269 if (p.sid != this.st.user.sid)
270 this.st.conn.send(JSON.stringify({code:"draw", target:p.sid}));
272 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
274 else if (this.drawOffer == "sent")
277 if (this.game.type == "corr")
278 GameStorage.update(this.gameRef.id, {drawOffer: false});
282 if (!confirm("Offer draw?"))
284 this.drawOffer = "sent";
285 this.people.forEach(p => {
286 if (p.sid != this.st.user.sid)
287 this.st.conn.send(JSON.stringify({code:"drawoffer", target:p.sid}));
289 if (this.game.type == "corr")
290 GameStorage.update(this.gameRef.id, {drawOffer: true});
293 abortGame: function() {
294 if (!confirm(this.st.tr["Terminate game?"]))
296 // Next line will trigger a "gameover" event, bubbling up till here
297 this.$refs["basegame"].endGame("?", "Abort");
298 this.people.forEach(p => {
299 if (p.sid != this.st.user.sid)
301 this.st.conn.send(JSON.stringify({
308 resign: function(e) {
309 if (!confirm("Resign the game?"))
311 this.people.forEach(p => {
312 if (p.sid != this.st.user.sid)
314 this.st.conn.send(JSON.stringify({code:"resign",
315 side:this.game.mycolor, target:p.sid}));
318 // Next line will trigger a "gameover" event, bubbling up till here
319 this.$refs["basegame"].endGame(
320 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
322 // 3 cases for loading a game:
323 // - from indexedDB (running or completed live game I play)
324 // - from server (one correspondance game I play[ed] or not)
325 // - from remote peer (one live game I don't play, finished or not)
326 loadGame: function(game, callback) {
327 const afterRetrieval = async (game) => {
328 const vModule = await import("@/variants/" + game.vname + ".js");
329 window.V = vModule.VariantRules;
330 this.vr = new V(game.fen);
331 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
332 const tc = extractTime(game.timeControl);
335 if (game.players[0].color == "b")
337 // Adopt the same convention for live and corr games: [0] = white
338 [ game.players[0], game.players[1] ] =
339 [ game.players[1], game.players[0] ];
341 // corr game: needs to compute the clocks + initime
342 // NOTE: clocks in seconds, initime in milliseconds
343 game.clocks = [tc.mainTime, tc.mainTime];
344 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
345 if (game.score == "*") //otherwise no need to bother with time
347 game.initime = [0, 0];
348 const L = game.moves.length;
351 let addTime = [0, 0];
352 for (let i=2; i<L; i++)
354 addTime[i%2] += tc.increment -
355 (game.moves[i].played - game.moves[i-1].played) / 1000;
357 for (let i=0; i<=1; i++)
358 game.clocks[i] += addTime[i];
361 game.initime[L%2] = game.moves[L-1].played;
363 this.drawOffer = "received";
365 // Now that we used idx and played, re-format moves as for live games
366 game.moves = game.moves.map( (m) => {
377 const myIdx = game.players.findIndex(p => {
378 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
380 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
382 game.clocks = [tc.mainTime, tc.mainTime];
383 if (game.score == "*")
385 game.initime[0] = Date.now();
388 // I play in this live game; corr games don't have clocks+initime
389 GameStorage.update(game.id,
392 initime: game.initime,
397 this.game = Object.assign({},
399 // NOTE: assign mycolor here, since BaseGame could also be VS computer
402 increment: tc.increment,
403 mycolor: [undefined,"w","b"][myIdx+1],
404 // opponent sid not strictly required (or available), but easier
405 // at least oppsid or oppid is available anyway:
406 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
407 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
410 if (!!this.lastate) //lastate arrived before game was loaded:
411 this.processLastate();
415 return afterRetrieval(game);
416 if (!!this.gameRef.rid)
418 // Remote live game: forgetting about callback func... (TODO: design)
419 this.st.conn.send(JSON.stringify(
420 {code:"askfullgame", target:this.gameRef.rid}));
424 // Local or corr game
425 GameStorage.get(this.gameRef.id, afterRetrieval);
428 // Post-process a move (which was just played)
429 processMove: function(move) {
430 if (!this.game.mycolor)
431 return; //I'm just an observer
432 // Update storage (corr or live)
433 const colorIdx = ["w","b"].indexOf(move.color);
434 // https://stackoverflow.com/a/38750895
435 const allowed_fields = ["appear", "vanish", "start", "end"];
436 const filtered_move = Object.keys(move)
437 .filter(key => allowed_fields.includes(key))
438 .reduce((obj, key) => {
439 obj[key] = move[key];
442 // Send move ("newmove" event) to people in the room (if our turn)
444 if (move.color == this.game.mycolor)
446 if (this.game.moves.length >= 2) //after first move
448 const elapsed = Date.now() - this.game.initime[colorIdx];
449 // elapsed time is measured in milliseconds
450 addTime = this.game.increment - elapsed/1000;
452 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
453 if (this.game.type == "corr")
454 sendMove.message = this.corrMsg;
455 this.people.forEach(p => {
456 if (p.sid != this.st.user.sid)
458 this.st.conn.send(JSON.stringify({
465 if (this.game.type == "corr" && this.corrMsg != "")
467 // Add message to last move in BaseGame:
468 // TODO: not very good style...
469 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
473 addTime = move.addTime; //supposed transmitted
474 const nextIdx = ["w","b"].indexOf(this.vr.turn);
475 // Since corr games are stored at only one location, update should be
476 // done only by one player for each move:
477 if (this.game.type == "live" || move.color == this.game.mycolor)
479 if (this.game.type == "corr")
481 GameStorage.update(this.gameRef.id,
486 squares: filtered_move,
487 message: this.corrMsg,
488 played: Date.now(), //TODO: on server?
489 idx: this.game.moves.length,
495 GameStorage.update(this.gameRef.id,
499 clocks: this.game.clocks.map((t,i) => i==colorIdx
500 ? this.game.clocks[i] + addTime
501 : this.game.clocks[i]),
502 initime: this.game.initime.map((t,i) => i==nextIdx
504 : this.game.initime[i]),
508 // Also update current game object:
509 this.game.moves.push(move);
510 this.game.fen = move.fen;
511 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
512 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
513 this.game.initime[nextIdx] = Date.now();
514 // Finally reset curMoveMessage if needed
515 if (this.game.type == "corr" && move.color == this.game.mycolor)
518 gameOver: function(score) {
519 this.game.mode = "analyze";
520 this.game.score = score;
521 const myIdx = this.game.players.findIndex(p => {
522 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
524 if (myIdx >= 0) //OK, I play in this game
525 GameStorage.update(this.gameRef.id, { score: score });