5 Chat(:players="game.players")
7 BaseGame(:game="game" :vr="vr" ref="basegame"
8 @newmove="processMove" @gameover="gameOver")
10 .col-sm-12.col-md-9.col-md-offset-3
11 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
12 button(@click="offerDraw") Draw
13 button(@click="abortGame") Abort
14 button(@click="resign") Resign
15 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
16 div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
17 div(v-if="game.type=='corr'") {{ game.corrMsg }}
18 textarea(v-if="game.score=='*'" v-model="corrMsg")
22 import BaseGame from "@/components/BaseGame.vue";
23 import Chat from "@/components/Chat.vue";
24 import { store } from "@/store";
25 import { GameStorage } from "@/utils/gameStorage";
26 import { ppt } from "@/utils/datetime";
27 import { extractTime } from "@/utils/timeControl";
28 import { ArrayFun } from "@/utils/array";
36 // gameRef: to find the game in (potentially remote) storage
40 gameRef: { //given in URL (rid = remote ID)
44 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
45 corrMsg: "", //to send offline messages in corr games
46 virtualClocks: [0, 0], //initialized with true game.clocks
47 vr: null, //"variant rules" object initialized from FEN
48 drawOffer: "", //TODO: use for button style
49 people: [], //players + observers
50 lastate: undefined, //used if opponent send lastate before game is ready
51 repeat: {}, //detect position repetition
55 "$route": function(to, from) {
56 this.gameRef.id = to.params["id"];
57 this.gameRef.rid = to.query["rid"];
60 "game.clocks": function(newState) {
61 if (this.game.moves.length < 2 || this.game.score != "*")
63 // 1st move not completed yet, or game over: freeze time
64 this.virtualClocks = newState.map(s => ppt(s));
67 const currentTurn = this.vr.turn;
68 const colorIdx = ["w","b"].indexOf(currentTurn);
69 let countdown = newState[colorIdx] -
70 (Date.now() - this.game.initime[colorIdx])/1000;
71 this.virtualClocks = [0,1].map(i => {
72 const removeTime = i == colorIdx
73 ? (Date.now() - this.game.initime[colorIdx])/1000
75 return ppt(newState[i] - removeTime);
77 let clockUpdate = setInterval(() => {
78 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
80 clearInterval(clockUpdate);
82 this.setScore(this.vr.turn=="w" ? "0-1" : "1-0", "Time");
86 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
87 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
92 // TODO: redundant code with Hall.vue (related to people array)
94 // Always add myself to players' list
95 const my = this.st.user;
96 this.people.push({sid:my.sid, id:my.id, name:my.name});
97 this.gameRef.id = this.$route.params["id"];
98 this.gameRef.rid = this.$route.query["rid"]; //may be undefined
99 // Define socket .onmessage() and .onclose() events:
100 this.st.conn.onmessage = this.socketMessageListener;
101 const socketCloseListener = () => {
102 store.socketCloseListener(); //reinitialize connexion (in store.js)
103 this.st.conn.addEventListener('message', this.socketMessageListener);
104 this.st.conn.addEventListener('close', socketCloseListener);
106 this.st.conn.onclose = socketCloseListener;
107 // Socket init required before loading remote game:
108 const socketInit = (callback) => {
109 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
111 else //socket not ready yet (initial loading)
112 this.st.conn.onopen = callback;
114 if (!this.gameRef.rid) //game stored locally or on server
115 this.loadGame(null, () => socketInit(this.roomInit));
116 else //game stored remotely: need socket to retrieve it
118 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
119 // --> It will be given when receiving "fullgame" socket event.
120 // A more general approach would be to store it somewhere.
121 socketInit(this.loadGame);
125 // O.1] Ask server for room composition:
126 roomInit: function() {
127 this.st.conn.send(JSON.stringify({code:"pollclients"}));
129 socketMessageListener: function(msg) {
130 const data = JSON.parse(msg.data);
134 alert("Warning: duplicate 'offline' connection");
136 // 0.2] Receive clients list (just socket IDs)
139 data.sockIds.forEach(sid => {
140 this.people.push({sid:sid, id:0, name:""});
142 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
148 // Request for identification: reply if I'm not anonymous
149 if (this.st.user.id > 0)
151 this.st.conn.send(JSON.stringify(
152 // people[0] instead of st.user to avoid sending email
153 {code:"identity", user:this.people[0], target:data.from}));
159 let player = this.people.find(p => p.sid == data.user.sid);
160 // NOTE: sometimes player.id fails because player is undefined...
161 // Probably because the event was meant for Hall?
164 player.id = data.user.id;
165 player.name = data.user.name;
166 // Sending last state only for live games: corr games are complete
167 if (this.game.type == "live" && this.game.oppsid == player.sid)
169 // Send our "last state" informations to opponent
170 const L = this.game.moves.length;
171 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
172 if (!!lastMove && this.drawOffer == "sent")
173 lastMove.draw = true;
174 this.st.conn.send(JSON.stringify({
180 score: this.game.score,
182 clocks: this.game.clocks,
189 // Send current (live) game
192 // Minimal game informations:
194 players: this.game.players.map(p => { return {name:p.name}; }),
196 timeControl: this.game.timeControl,
198 this.st.conn.send(JSON.stringify({code:"game",
199 game:myGame, target:data.from}));
202 this.corrMsg = data.move.message; //may be empty
203 this.$set(this.game, "moveToPlay", data.move); //TODO: Vue3...
205 case "lastate": //got opponent infos about last move
208 if (!!this.game.type) //game is loaded
209 this.processLastate();
210 //else: will be processed when game is ready
214 this.setScore(data.side=="b" ? "1-0" : "0-1", "Resign");
217 this.setScore("?", "Abort");
220 this.setScore("1/2", "Mutual agreement");
223 this.drawOffer = "received"; //TODO: observers don't know who offered draw
226 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
229 // Callback "roomInit" to poll clients only after game is loaded
230 this.loadGame(data.game, this.roomInit);
234 this.people.push({name:"", id:0, sid:data.from});
235 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
239 ArrayFun.remove(this.people, p => p.sid == data.from);
243 // lastate was received, but maybe game wasn't ready yet:
244 processLastate: function() {
245 const data = this.lastate;
246 this.lastate = undefined; //security...
247 const L = this.game.moves.length;
248 if (data.movesCount > L)
250 // Just got last move from him
251 this.$set(this.game, "moveToPlay", data.lastMove);
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.setScore(data.score, "Opponent action");
258 this.game.clocks = data.clocks; //TODO: check this?
259 if (!!data.lastMove.draw)
260 this.drawOffer = "received";
263 setScore: function(score, message) {
264 this.game.scoreMsg = message;
265 this.$set(this.game, "score", score); //TODO: Vue3...
267 offerDraw: function() {
268 if (this.drawOffer == "received")
270 if (!confirm("Accept draw?"))
272 this.people.forEach(p => {
273 if (p.sid != this.st.user.sid)
274 this.st.conn.send(JSON.stringify({code:"draw", target:p.sid}));
276 this.setScore("1/2", "Mutual agreement");
278 else if (this.drawOffer == "sent")
281 if (this.game.type == "corr")
282 GameStorage.update(this.gameRef.id, {drawOffer: false});
286 if (!confirm("Offer draw?"))
288 this.drawOffer = "sent";
289 this.people.forEach(p => {
290 if (p.sid != this.st.user.sid)
291 this.st.conn.send(JSON.stringify({code:"drawoffer", target:p.sid}));
293 if (this.game.type == "corr")
294 GameStorage.update(this.gameRef.id, {drawOffer: true});
297 abortGame: function() {
298 if (!confirm(this.st.tr["Terminate game?"]))
300 this.setScore("?", "Abort");
301 this.people.forEach(p => {
302 if (p.sid != this.st.user.sid)
304 this.st.conn.send(JSON.stringify({
311 resign: function(e) {
312 if (!confirm("Resign the game?"))
314 this.people.forEach(p => {
315 if (p.sid != this.st.user.sid)
317 this.st.conn.send(JSON.stringify({code:"resign",
318 side:this.game.mycolor, target:p.sid}));
321 this.setScore(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
323 // 3 cases for loading a game:
324 // - from indexedDB (running or completed live game I play)
325 // - from server (one correspondance game I play[ed] or not)
326 // - from remote peer (one live game I don't play, finished or not)
327 loadGame: function(game, callback) {
328 const afterRetrieval = async (game) => {
329 const vModule = await import("@/variants/" + game.vname + ".js");
330 window.V = vModule.VariantRules;
331 this.vr = new V(game.fen);
332 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
333 const tc = extractTime(game.timeControl);
336 if (game.players[0].color == "b")
338 // Adopt the same convention for live and corr games: [0] = white
339 [ game.players[0], game.players[1] ] =
340 [ game.players[1], game.players[0] ];
342 // corr game: needs to compute the clocks + initime
343 // NOTE: clocks in seconds, initime in milliseconds
344 game.clocks = [tc.mainTime, tc.mainTime];
345 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
346 if (game.score == "*") //otherwise no need to bother with time
348 game.initime = [0, 0];
349 const L = game.moves.length;
352 let addTime = [0, 0];
353 for (let i=2; i<L; i++)
355 addTime[i%2] += tc.increment -
356 (game.moves[i].played - game.moves[i-1].played) / 1000;
358 for (let i=0; i<=1; i++)
359 game.clocks[i] += addTime[i];
362 game.initime[L%2] = game.moves[L-1].played;
364 this.drawOffer = "received";
366 // Now that we used idx and played, re-format moves as for live games
367 game.moves = game.moves.map( (m) => {
378 const myIdx = game.players.findIndex(p => {
379 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
381 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
383 game.clocks = [tc.mainTime, tc.mainTime];
384 if (game.score == "*")
386 game.initime[0] = Date.now();
389 // I play in this live game; corr games don't have clocks+initime
390 GameStorage.update(game.id,
393 initime: game.initime,
398 this.game = Object.assign({},
400 // NOTE: assign mycolor here, since BaseGame could also be VS computer
403 increment: tc.increment,
404 mycolor: [undefined,"w","b"][myIdx+1],
405 // opponent sid not strictly required (or available), but easier
406 // at least oppsid or oppid is available anyway:
407 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
408 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
411 this.repeat = {}; //reset
412 if (!!this.lastate) //lastate arrived before game was loaded:
413 this.processLastate();
417 return afterRetrieval(game);
418 if (!!this.gameRef.rid)
420 // Remote live game: forgetting about callback func... (TODO: design)
421 this.st.conn.send(JSON.stringify(
422 {code:"askfullgame", target:this.gameRef.rid}));
426 // Local or corr game
427 GameStorage.get(this.gameRef.id, afterRetrieval);
430 // Post-process a move (which was just played)
431 processMove: function(move) {
432 if (!this.game.mycolor)
433 return; //I'm just an observer
434 // Update storage (corr or live)
435 const colorIdx = ["w","b"].indexOf(move.color);
436 // https://stackoverflow.com/a/38750895
437 const allowed_fields = ["appear", "vanish", "start", "end"];
438 const filtered_move = Object.keys(move)
439 .filter(key => allowed_fields.includes(key))
440 .reduce((obj, key) => {
441 obj[key] = move[key];
444 // Send move ("newmove" event) to people in the room (if our turn)
446 if (move.color == this.game.mycolor)
448 if (this.game.moves.length >= 2) //after first move
450 const elapsed = Date.now() - this.game.initime[colorIdx];
451 // elapsed time is measured in milliseconds
452 addTime = this.game.increment - elapsed/1000;
454 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
455 if (this.game.type == "corr")
456 sendMove.message = this.corrMsg;
457 this.people.forEach(p => {
458 if (p.sid != this.st.user.sid)
460 this.st.conn.send(JSON.stringify({
469 addTime = move.addTime; //supposed transmitted
470 const nextIdx = ["w","b"].indexOf(this.vr.turn);
471 // Since corr games are stored at only one location, update should be
472 // done only by one player for each move:
473 if (this.game.type == "live" || move.color == this.game.mycolor)
475 if (this.game.type == "corr")
477 GameStorage.update(this.gameRef.id,
480 message: this.corrMsg,
483 squares: filtered_move,
484 played: Date.now(), //TODO: on server?
485 idx: this.game.moves.length,
491 GameStorage.update(this.gameRef.id,
495 clocks: this.game.clocks.map((t,i) => i==colorIdx
496 ? this.game.clocks[i] + addTime
497 : this.game.clocks[i]),
498 initime: this.game.initime.map((t,i) => i==nextIdx
500 : this.game.initime[i]),
504 // Also update current game object:
505 this.game.moves.push(move);
506 this.game.fen = move.fen;
507 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
508 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
509 this.game.initime[nextIdx] = Date.now();
510 // If repetition detected, consider that a draw offer was received:
511 const fenObj = V.ParseFen(move.fen);
512 let repIdx = fenObj.position + "_" + fenObj.turn;
514 repIdx += "_" + fenObj.flags;
515 this.repeat[repIdx] = (!!this.repeat[repIdx]
516 ? this.repeat[repIdx]+1
518 if (this.repeat[repIdx] >= 3)
519 this.drawOffer = "received"; //TODO: will print "mutual agreement"...
521 gameOver: function(score) {
522 this.game.mode = "analyze";
523 this.game.score = score; //until Vue3, this property change isn't seen
524 //by child (and doesn't need to be)
525 const myIdx = this.game.players.findIndex(p => {
526 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
528 if (myIdx >= 0) //OK, I play in this game
529 GameStorage.update(this.gameRef.id, { score: score });
537 background-color: green
540 background-color: red
543 background-color: white
546 background-color: black