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
48 "$route": function(to, from) {
49 this.gameRef.id = to.params["id"];
50 this.gameRef.rid = to.query["rid"];
53 "game.clocks": function(newState) {
54 if (this.game.moves.length < 2)
56 // 1st move not completed yet: freeze time
57 this.virtualClocks = newState.map(s => ppt(s));
60 const currentTurn = this.vr.turn;
61 const colorIdx = ["w","b"].indexOf(currentTurn);
62 let countdown = newState[colorIdx] -
63 (Date.now() - this.game.initime[colorIdx])/1000;
64 this.virtualClocks = [0,1].map(i => {
65 const removeTime = i == colorIdx
66 ? (Date.now() - this.game.initime[colorIdx])/1000
68 return ppt(newState[i] - removeTime);
70 let clockUpdate = setInterval(() => {
71 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
73 clearInterval(clockUpdate);
76 this.$refs["basegame"].endGame(
77 this.vr.turn=="w" ? "0-1" : "1-0", "Time");
82 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
83 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
88 // TODO: redundant code with Hall.vue (related to people array)
90 // Always add myself to players' list
91 const my = this.st.user;
92 this.people.push({sid:my.sid, id:my.id, name:my.name});
93 this.gameRef.id = this.$route.params["id"];
94 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
95 if (!this.gameRef.rid)
96 this.loadGame(); //local or corr: can load from now
97 // 0.1] Ask server for room composition:
98 const initialize = () => {
99 // Poll clients + load game if stored remotely
100 this.st.conn.send(JSON.stringify({code:"pollclients"}));
101 if (!!this.gameRef.rid)
104 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
106 else //socket not ready yet (initial loading)
107 this.st.conn.onopen = initialize;
108 this.st.conn.onmessage = this.socketMessageListener;
109 const socketCloseListener = () => {
110 store.socketCloseListener(); //reinitialize connexion (in store.js)
111 this.st.conn.addEventListener('message', this.socketMessageListener);
112 this.st.conn.addEventListener('close', socketCloseListener);
114 this.st.conn.onclose = socketCloseListener;
117 getOppSid: function() {
118 if (!!this.game.oppsid)
119 return this.game.oppsid;
120 const opponent = this.people.find(p => p.id == this.game.oppid);
121 return (!!opponent ? opponent.sid : null);
123 socketMessageListener: function(msg) {
124 const data = JSON.parse(msg.data);
127 // 0.2] Receive clients list (just socket IDs)
130 data.sockIds.forEach(sid => {
131 this.people.push({sid:sid, id:0, name:""});
133 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
139 // Request for identification: reply if I'm not anonymous
140 if (this.st.user.id > 0)
142 this.st.conn.send(JSON.stringify(
143 // people[0] instead of st.user to avoid sending email
144 {code:"identity", user:this.people[0], target:data.from}));
150 let player = this.people.find(p => p.sid == data.user.sid);
151 // NOTE: sometimes player.id fails because player is undefined...
152 // Probably because the event was meant for Hall?
155 player.id = data.user.id;
156 player.name = data.user.name;
157 // Sending last state only for live games: corr games are complete
158 if (this.game.type == "live" && this.game.oppsid == player.sid)
160 // Send our "last state" informations to opponent
161 const L = this.game.moves.length;
162 this.st.conn.send(JSON.stringify({
167 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
168 score: this.game.score,
170 drawOffer: this.drawOffer,
171 clocks: this.game.clocks,
178 // Send current (live) game
181 // Minimal game informations:
183 players: this.game.players.map(p => { return {name:p.name}; }),
185 timeControl: this.game.timeControl,
187 this.st.conn.send(JSON.stringify({code:"game",
188 game:myGame, target:data.from}));
191 // NOTE: this call to play() will trigger processMove()
192 this.$refs["basegame"].play(data.move,
193 "receive", this.game.vname!="Dark" ? "animate" : null);
195 case "lastate": //got opponent infos about last move
197 const L = this.game.moves.length;
198 if (data.movesCount > L)
200 // Just got last move from him
201 this.$refs["basegame"].play(data.lastMove,
202 "receive", this.game.vname!="Dark" ? "animate" : null);
203 if (data.score != "*" && this.game.score == "*")
205 // Opponent resigned or aborted game, or accepted draw offer
206 // (this is not a stalemate or checkmate)
207 this.$refs["basegame"].endGame(data.score, "Opponent action");
209 this.game.clocks = data.clocks; //TODO: check this?
210 this.drawOffer = data.drawOffer; //does opponent offer draw?
215 this.$refs["basegame"].endGame(
216 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
219 this.$refs["basegame"].endGame("?", "Abort");
222 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
225 this.drawOffer = "received";
228 // TODO: use data.id to retrieve game in indexedDB (but for now only one running game so OK)
229 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
232 this.loadGame(data.game);
234 // TODO: drawaccepted (click draw button before sending move
235 // ==> draw offer in move)
236 // ==> on "newmove", check "drawOffer" field
239 this.people.push({name:"", id:0, sid:data.from});
240 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
244 ArrayFun.remove(this.people, p => p.sid == data.from);
248 offerDraw: function() {
249 // TODO: also for corr games
250 if (this.drawOffer == "received")
252 if (!confirm("Accept draw?"))
254 const oppsid = this.getOppSid();
256 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
257 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
259 else if (this.drawOffer == "sent")
263 if (!confirm("Offer draw?"))
265 const oppsid = this.getOppSid();
267 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
270 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
271 receiveDrawOffer: function() {
273 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
274 // if accept: send message "draw"
276 abortGame: function() {
277 if (!confirm(this.st.tr["Terminate game?"]))
279 // Next line will trigger a "gameover" event, bubbling up till here
280 this.$refs["basegame"].endGame("?", "Abort");
281 this.people.forEach(p => {
282 if (p.sid != this.st.user.sid)
284 this.st.conn.send(JSON.stringify({
291 resign: function(e) {
292 if (!confirm("Resign the game?"))
294 const oppsid = this.getOppSid();
297 this.st.conn.send(JSON.stringify({
302 // Next line will trigger a "gameover" event, bubbling up till here
303 this.$refs["basegame"].endGame(
304 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
306 // 3 cases for loading a game:
307 // - from indexedDB (running or completed live game I play)
308 // - from server (one correspondance game I play[ed] or not)
309 // - from remote peer (one live game I don't play, finished or not)
310 loadGame: function(game) {
311 const afterRetrieval = async (game) => {
312 const vModule = await import("@/variants/" + game.vname + ".js");
313 window.V = vModule.VariantRules;
314 this.vr = new V(game.fen);
315 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
316 const tc = extractTime(game.timeControl);
319 if (game.players[0].color == "b")
321 // Adopt the same convention for live and corr games: [0] = white
322 [ game.players[0], game.players[1] ] =
323 [ game.players[1], game.players[0] ];
325 // corr game: needs to compute the clocks + initime
326 // NOTE: clocks in seconds, initime in milliseconds
327 game.clocks = [tc.mainTime, tc.mainTime];
328 game.initime = [0, 0];
329 const L = game.moves.length;
330 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
333 let addTime = [0, 0];
334 for (let i=2; i<L; i++)
336 addTime[i%2] += tc.increment -
337 (game.moves[i].played - game.moves[i-1].played) / 1000;
339 for (let i=0; i<=1; i++)
340 game.clocks[i] += addTime[i];
343 game.initime[L%2] = game.moves[L-1].played;
344 // Now that we used idx and played, re-format moves as for live games
345 game.moves = game.moves.map( (m) => {
356 const myIdx = game.players.findIndex(p => {
357 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
359 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
361 game.clocks = [tc.mainTime, tc.mainTime];
362 game.initime[0] = Date.now();
365 // I play in this live game; corr games don't have clocks+initime
366 GameStorage.update(game.id,
369 initime: game.initime,
373 this.game = Object.assign({},
375 // NOTE: assign mycolor here, since BaseGame could also be VS computer
378 increment: tc.increment,
379 mycolor: [undefined,"w","b"][myIdx+1],
380 // opponent sid not strictly required (or available), but easier
381 // at least oppsid or oppid is available anyway:
382 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
383 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
388 return afterRetrieval(game);
389 if (!!this.gameRef.rid)
392 // (TODO: send game ID as well, and receiver would pick the corresponding
393 // game in his current games; if allowed to play several)
394 this.st.conn.send(JSON.stringify(
395 {code:"askfullgame", target:this.gameRef.rid}));
396 // (send moves updates + resign/abort/draw actions)
400 // Local or corr game
401 GameStorage.get(this.gameRef.id, afterRetrieval);
404 // Post-process a move (which was just played)
405 processMove: function(move) {
406 if (!this.game.mycolor)
407 return; //I'm just an observer
408 // Update storage (corr or live)
409 const colorIdx = ["w","b"].indexOf(move.color);
410 // https://stackoverflow.com/a/38750895
411 const allowed_fields = ["appear", "vanish", "start", "end"];
412 const filtered_move = Object.keys(move)
413 .filter(key => allowed_fields.includes(key))
414 .reduce((obj, key) => {
415 obj[key] = move[key];
418 // Send move ("newmove" event) to people in the room (if our turn)
420 if (move.color == this.game.mycolor)
422 if (this.game.moves.length >= 2) //after first move
424 const elapsed = Date.now() - this.game.initime[colorIdx];
425 // elapsed time is measured in milliseconds
426 addTime = this.game.increment - elapsed/1000;
428 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
429 if (this.game.type == "corr")
430 sendMove.message = this.corrMsg;
431 const oppsid = this.getOppSid();
432 this.people.forEach(p => {
433 if (p.sid != this.st.user.sid)
435 this.st.conn.send(JSON.stringify({
442 if (this.game.type == "corr" && this.corrMsg != "")
444 // Add message to last move in BaseGame:
445 // TODO: not very good style...
446 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
450 addTime = move.addTime; //supposed transmitted
451 const nextIdx = ["w","b"].indexOf(this.vr.turn);
452 // Since corr games are stored at only one location, update should be
453 // done only by one player for each move:
454 if (this.game.type == "live" || move.color == this.game.mycolor)
456 if (this.game.type == "corr")
458 GameStorage.update(this.gameRef.id,
463 squares: filtered_move,
464 message: this.corrMsg,
465 played: Date.now(), //TODO: on server?
466 idx: this.game.moves.length,
472 GameStorage.update(this.gameRef.id,
476 clocks: this.game.clocks.map((t,i) => i==colorIdx
477 ? this.game.clocks[i] + addTime
478 : this.game.clocks[i]),
479 initime: this.game.initime.map((t,i) => i==nextIdx
481 : this.game.initime[i]),
485 // Also update current game object:
486 this.game.moves.push(move);
487 this.game.fen = move.fen;
488 //TODO: just this.game.clocks[colorIdx] += addTime;
489 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
490 this.game.initime[nextIdx] = Date.now();
491 // Finally reset curMoveMessage if needed
492 if (this.game.type == "corr" && move.color == this.game.mycolor)
495 gameOver: function(score) {
496 this.game.mode = "analyze";
497 this.game.score = score;
498 const myIdx = this.game.players.findIndex(p => {
499 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
501 if (myIdx >= 0) //OK, I play in this game
502 GameStorage.update(this.gameRef.id, { score: score });