4 #chat.col-sm-12.col-md-4.col-md-offset-4
5 Chat(:players="game.players" :pastChats="game.chats"
6 @newchat="processChat")
9 #actions(v-if="game.mode!='analyze' && game.score=='*'")
10 button(@click="offerDraw") Draw
11 button(@click="abortGame") Abort
12 button(@click="resign") Resign
13 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
14 div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
15 BaseGame(:game="game" :vr="vr" ref="basegame"
16 @newmove="processMove" @gameover="gameOver")
20 import BaseGame from "@/components/BaseGame.vue";
21 import Chat from "@/components/Chat.vue";
22 import { store } from "@/store";
23 import { GameStorage } from "@/utils/gameStorage";
24 import { ppt } from "@/utils/datetime";
25 import { extractTime } from "@/utils/timeControl";
26 import { ArrayFun } from "@/utils/array";
34 // gameRef: to find the game in (potentially remote) storage
38 gameRef: { //given in URL (rid = remote ID)
42 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
43 virtualClocks: [0, 0], //initialized with true game.clocks
44 vr: null, //"variant rules" object initialized from FEN
45 drawOffer: "", //TODO: use for button style
46 people: [], //players + observers
47 lastate: undefined, //used if opponent send lastate before game is ready
48 repeat: {}, //detect position repetition
52 "$route": function(to, from) {
53 this.gameRef.id = to.params["id"];
54 this.gameRef.rid = to.query["rid"];
57 "game.clocks": function(newState) {
58 if (this.game.moves.length < 2 || this.game.score != "*")
60 // 1st move not completed yet, or game over: freeze time
61 this.virtualClocks = newState.map(s => ppt(s));
64 const currentTurn = this.vr.turn;
65 const colorIdx = ["w","b"].indexOf(currentTurn);
66 let countdown = newState[colorIdx] -
67 (Date.now() - this.game.initime[colorIdx])/1000;
68 this.virtualClocks = [0,1].map(i => {
69 const removeTime = i == colorIdx
70 ? (Date.now() - this.game.initime[colorIdx])/1000
72 return ppt(newState[i] - removeTime);
74 let clockUpdate = setInterval(() => {
75 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
77 clearInterval(clockUpdate);
79 this.gameOver(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 this.$set(this.game, "moveToPlay", data.move); //TODO: Vue3...
201 case "lastate": //got opponent infos about last move
204 if (!!this.game.type) //game is loaded
205 this.processLastate();
206 //else: will be processed when game is ready
210 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
213 this.gameOver("?", "Abort");
216 this.gameOver("1/2", "Mutual agreement");
219 this.drawOffer = "received"; //TODO: observers don't know who offered draw
222 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
225 // Callback "roomInit" to poll clients only after game is loaded
226 this.loadGame(data.game, this.roomInit);
230 this.people.push({name:"", id:0, sid:data.from});
231 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
235 ArrayFun.remove(this.people, p => p.sid == data.from);
239 // lastate was received, but maybe game wasn't ready yet:
240 processLastate: function() {
241 const data = this.lastate;
242 this.lastate = undefined; //security...
243 const L = this.game.moves.length;
244 if (data.movesCount > L)
246 // Just got last move from him
247 this.$set(this.game, "moveToPlay", data.lastMove);
248 if (data.score != "*" && this.game.score == "*")
250 // Opponent resigned or aborted game, or accepted draw offer
251 // (this is not a stalemate or checkmate)
252 this.gameOver(data.score, "Opponent action");
254 this.game.clocks = data.clocks; //TODO: check this?
255 if (!!data.lastMove.draw)
256 this.drawOffer = "received";
259 offerDraw: function() {
260 if (this.drawOffer == "received")
262 if (!confirm("Accept draw?"))
264 this.people.forEach(p => {
265 if (p.sid != this.st.user.sid)
266 this.st.conn.send(JSON.stringify({code:"draw", target:p.sid}));
268 this.gameOver("1/2", "Mutual agreement");
270 else if (this.drawOffer == "sent")
273 if (this.game.type == "corr")
274 GameStorage.update(this.gameRef.id, {drawOffer: false});
278 if (!confirm("Offer draw?"))
280 this.drawOffer = "sent";
281 this.people.forEach(p => {
282 if (p.sid != this.st.user.sid)
283 this.st.conn.send(JSON.stringify({code:"drawoffer", target:p.sid}));
285 if (this.game.type == "corr")
286 GameStorage.update(this.gameRef.id, {drawOffer: true});
289 abortGame: function() {
290 if (!confirm(this.st.tr["Terminate game?"]))
292 this.gameOver("?", "Abort");
293 this.people.forEach(p => {
294 if (p.sid != this.st.user.sid)
296 this.st.conn.send(JSON.stringify({
303 resign: function(e) {
304 if (!confirm("Resign the game?"))
306 this.people.forEach(p => {
307 if (p.sid != this.st.user.sid)
309 this.st.conn.send(JSON.stringify({code:"resign",
310 side:this.game.mycolor, target:p.sid}));
313 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
315 // 3 cases for loading a game:
316 // - from indexedDB (running or completed live game I play)
317 // - from server (one correspondance game I play[ed] or not)
318 // - from remote peer (one live game I don't play, finished or not)
319 loadGame: function(game, callback) {
320 const afterRetrieval = async (game) => {
321 const vModule = await import("@/variants/" + game.vname + ".js");
322 window.V = vModule.VariantRules;
323 this.vr = new V(game.fen);
324 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
325 const tc = extractTime(game.timeControl);
328 if (game.players[0].color == "b")
330 // Adopt the same convention for live and corr games: [0] = white
331 [ game.players[0], game.players[1] ] =
332 [ game.players[1], game.players[0] ];
334 // corr game: needs to compute the clocks + initime
335 // NOTE: clocks in seconds, initime in milliseconds
336 game.clocks = [tc.mainTime, tc.mainTime];
337 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
338 if (game.score == "*") //otherwise no need to bother with time
340 game.initime = [0, 0];
341 const L = game.moves.length;
344 let addTime = [0, 0];
345 for (let i=2; i<L; i++)
347 addTime[i%2] += tc.increment -
348 (game.moves[i].played - game.moves[i-1].played) / 1000;
350 for (let i=0; i<=1; i++)
351 game.clocks[i] += addTime[i];
354 game.initime[L%2] = game.moves[L-1].played;
356 this.drawOffer = "received";
358 // Now that we used idx and played, re-format moves as for live games
359 game.moves = game.moves.map( (m) => {
368 // Also sort chat messages (if any)
369 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
371 const myIdx = game.players.findIndex(p => {
372 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
374 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
376 game.clocks = [tc.mainTime, tc.mainTime];
377 if (game.score == "*")
379 game.initime[0] = Date.now();
382 // I play in this live game; corr games don't have clocks+initime
383 GameStorage.update(game.id,
386 initime: game.initime,
391 this.game = Object.assign({},
393 // NOTE: assign mycolor here, since BaseGame could also be VS computer
396 increment: tc.increment,
397 mycolor: [undefined,"w","b"][myIdx+1],
398 // opponent sid not strictly required (or available), but easier
399 // at least oppsid or oppid is available anyway:
400 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
401 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
404 this.repeat = {}; //reset
405 if (!!this.lastate) //lastate arrived before game was loaded:
406 this.processLastate();
410 return afterRetrieval(game);
411 if (!!this.gameRef.rid)
413 // Remote live game: forgetting about callback func... (TODO: design)
414 this.st.conn.send(JSON.stringify(
415 {code:"askfullgame", target:this.gameRef.rid}));
419 // Local or corr game
420 GameStorage.get(this.gameRef.id, afterRetrieval);
423 // Post-process a move (which was just played)
424 processMove: function(move) {
425 if (!this.game.mycolor)
426 return; //I'm just an observer
427 // Update storage (corr or live)
428 const colorIdx = ["w","b"].indexOf(move.color);
429 // https://stackoverflow.com/a/38750895
430 const allowed_fields = ["appear", "vanish", "start", "end"];
431 const filtered_move = Object.keys(move)
432 .filter(key => allowed_fields.includes(key))
433 .reduce((obj, key) => {
434 obj[key] = move[key];
437 // Send move ("newmove" event) to people in the room (if our turn)
439 if (move.color == this.game.mycolor)
441 if (this.game.moves.length >= 2) //after first move
443 const elapsed = Date.now() - this.game.initime[colorIdx];
444 // elapsed time is measured in milliseconds
445 addTime = this.game.increment - elapsed/1000;
447 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
448 this.people.forEach(p => {
449 if (p.sid != this.st.user.sid)
451 this.st.conn.send(JSON.stringify({
460 addTime = move.addTime; //supposed transmitted
461 const nextIdx = ["w","b"].indexOf(this.vr.turn);
462 // Since corr games are stored at only one location, update should be
463 // done only by one player for each move:
464 if (this.game.type == "live" || move.color == this.game.mycolor)
466 if (this.game.type == "corr")
468 GameStorage.update(this.gameRef.id,
473 squares: filtered_move,
474 played: Date.now(), //TODO: on server?
475 idx: this.game.moves.length,
481 GameStorage.update(this.gameRef.id,
485 clocks: this.game.clocks.map((t,i) => i==colorIdx
486 ? this.game.clocks[i] + addTime
487 : this.game.clocks[i]),
488 initime: this.game.initime.map((t,i) => i==nextIdx
490 : this.game.initime[i]),
494 // Also update current game object:
495 this.game.moves.push(move);
496 this.game.fen = move.fen;
497 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
498 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
499 this.game.initime[nextIdx] = Date.now();
500 // If repetition detected, consider that a draw offer was received:
501 const fenObj = V.ParseFen(move.fen);
502 let repIdx = fenObj.position + "_" + fenObj.turn;
504 repIdx += "_" + fenObj.flags;
505 this.repeat[repIdx] = (!!this.repeat[repIdx]
506 ? this.repeat[repIdx]+1
508 if (this.repeat[repIdx] >= 3)
509 this.drawOffer = "received"; //TODO: will print "mutual agreement"...
511 processChat: function(chat) {
512 if (this.game.type == "corr")
513 GameStorage.update(this.gameRef.id, {chat: chat});
515 gameOver: function(score, scoreMsg) {
516 this.game.mode = "analyze";
517 this.game.score = score;
518 this.game.scoreMsg = scoreMsg;
519 const myIdx = this.game.players.findIndex(p => {
520 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
522 if (myIdx >= 0) //OK, I play in this game
523 GameStorage.update(this.gameRef.id, { score: score });
531 background-color: green
533 background-color: red
535 @media screen and (min-width: 768px)
538 @media screen and (max-width: 767px)
547 display: inline-block