4 #chat.col-sm-12.col-md-4.col-md-offset-4
5 Chat(:players="game.players" @newchat="processChat")
8 #actions(v-if="game.mode!='analyze' && game.score=='*'")
9 button(@click="offerDraw") Draw
10 button(@click="abortGame") Abort
11 button(@click="resign") Resign
12 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
13 div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
14 BaseGame(:game="game" :vr="vr" ref="basegame"
15 @newmove="processMove" @gameover="gameOver")
19 import BaseGame from "@/components/BaseGame.vue";
20 import Chat from "@/components/Chat.vue";
21 import { store } from "@/store";
22 import { GameStorage } from "@/utils/gameStorage";
23 import { ppt } from "@/utils/datetime";
24 import { extractTime } from "@/utils/timeControl";
25 import { ArrayFun } from "@/utils/array";
33 // gameRef: to find the game in (potentially remote) storage
37 gameRef: { //given in URL (rid = remote ID)
41 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
42 virtualClocks: [0, 0], //initialized with true game.clocks
43 vr: null, //"variant rules" object initialized from FEN
44 drawOffer: "", //TODO: use for button style
45 people: [], //players + observers
46 lastate: undefined, //used if opponent send lastate before game is ready
47 repeat: {}, //detect position repetition
51 "$route": function(to, from) {
52 this.gameRef.id = to.params["id"];
53 this.gameRef.rid = to.query["rid"];
56 "game.clocks": function(newState) {
57 if (this.game.moves.length < 2 || this.game.score != "*")
59 // 1st move not completed yet, or game over: freeze time
60 this.virtualClocks = newState.map(s => ppt(s));
63 const currentTurn = this.vr.turn;
64 const colorIdx = ["w","b"].indexOf(currentTurn);
65 let countdown = newState[colorIdx] -
66 (Date.now() - this.game.initime[colorIdx])/1000;
67 this.virtualClocks = [0,1].map(i => {
68 const removeTime = i == colorIdx
69 ? (Date.now() - this.game.initime[colorIdx])/1000
71 return ppt(newState[i] - removeTime);
73 let clockUpdate = setInterval(() => {
74 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
76 clearInterval(clockUpdate);
78 this.gameOver(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 // Define socket .onmessage() and .onclose() events:
96 this.st.conn.onmessage = this.socketMessageListener;
97 const socketCloseListener = () => {
98 store.socketCloseListener(); //reinitialize connexion (in store.js)
99 this.st.conn.addEventListener('message', this.socketMessageListener);
100 this.st.conn.addEventListener('close', socketCloseListener);
102 this.st.conn.onclose = socketCloseListener;
103 // Socket init required before loading remote game:
104 const socketInit = (callback) => {
105 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
107 else //socket not ready yet (initial loading)
108 this.st.conn.onopen = callback;
110 if (!this.gameRef.rid) //game stored locally or on server
111 this.loadGame(null, () => socketInit(this.roomInit));
112 else //game stored remotely: need socket to retrieve it
114 // NOTE: the callback "roomInit" will be lost, so we don't provide it.
115 // --> It will be given when receiving "fullgame" socket event.
116 // A more general approach would be to store it somewhere.
117 socketInit(this.loadGame);
121 // O.1] Ask server for room composition:
122 roomInit: function() {
123 this.st.conn.send(JSON.stringify({code:"pollclients"}));
125 socketMessageListener: function(msg) {
126 const data = JSON.parse(msg.data);
130 alert("Warning: duplicate 'offline' connection");
132 // 0.2] Receive clients list (just socket IDs)
135 data.sockIds.forEach(sid => {
136 this.people.push({sid:sid, id:0, name:""});
138 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
144 // Request for identification: reply if I'm not anonymous
145 if (this.st.user.id > 0)
147 this.st.conn.send(JSON.stringify(
148 // people[0] instead of st.user to avoid sending email
149 {code:"identity", user:this.people[0], target:data.from}));
155 let player = this.people.find(p => p.sid == data.user.sid);
156 // NOTE: sometimes player.id fails because player is undefined...
157 // Probably because the event was meant for Hall?
160 player.id = data.user.id;
161 player.name = data.user.name;
162 // Sending last state only for live games: corr games are complete
163 if (this.game.type == "live" && this.game.oppsid == player.sid)
165 // Send our "last state" informations to opponent
166 const L = this.game.moves.length;
167 let lastMove = (L>0 ? this.game.moves[L-1] : undefined);
168 if (!!lastMove && this.drawOffer == "sent")
169 lastMove.draw = true;
170 this.st.conn.send(JSON.stringify({
176 score: this.game.score,
178 clocks: this.game.clocks,
185 // Send current (live) game
188 // Minimal game informations:
190 players: this.game.players.map(p => { return {name:p.name}; }),
192 timeControl: this.game.timeControl,
194 this.st.conn.send(JSON.stringify({code:"game",
195 game:myGame, target:data.from}));
198 this.$set(this.game, "moveToPlay", data.move); //TODO: Vue3...
200 case "lastate": //got opponent infos about last move
203 if (!!this.game.type) //game is loaded
204 this.processLastate();
205 //else: will be processed when game is ready
209 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
212 this.gameOver("?", "Abort");
215 this.gameOver("1/2", "Mutual agreement");
218 this.drawOffer = "received"; //TODO: observers don't know who offered draw
221 this.st.conn.send(JSON.stringify({code:"fullgame", game:this.game, target:data.from}));
224 // Callback "roomInit" to poll clients only after game is loaded
225 this.loadGame(data.game, this.roomInit);
229 this.people.push({name:"", id:0, sid:data.from});
230 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
234 ArrayFun.remove(this.people, p => p.sid == data.from);
238 // lastate was received, but maybe game wasn't ready yet:
239 processLastate: function() {
240 const data = this.lastate;
241 this.lastate = undefined; //security...
242 const L = this.game.moves.length;
243 if (data.movesCount > L)
245 // Just got last move from him
246 this.$set(this.game, "moveToPlay", data.lastMove);
247 if (data.score != "*" && this.game.score == "*")
249 // Opponent resigned or aborted game, or accepted draw offer
250 // (this is not a stalemate or checkmate)
251 this.gameOver(data.score, "Opponent action");
253 this.game.clocks = data.clocks; //TODO: check this?
254 if (!!data.lastMove.draw)
255 this.drawOffer = "received";
258 offerDraw: function() {
259 if (this.drawOffer == "received")
261 if (!confirm("Accept draw?"))
263 this.people.forEach(p => {
264 if (p.sid != this.st.user.sid)
265 this.st.conn.send(JSON.stringify({code:"draw", target:p.sid}));
267 this.gameOver("1/2", "Mutual agreement");
269 else if (this.drawOffer == "sent")
272 if (this.game.type == "corr")
273 GameStorage.update(this.gameRef.id, {drawOffer: false});
277 if (!confirm("Offer draw?"))
279 this.drawOffer = "sent";
280 this.people.forEach(p => {
281 if (p.sid != this.st.user.sid)
282 this.st.conn.send(JSON.stringify({code:"drawoffer", target:p.sid}));
284 if (this.game.type == "corr")
285 GameStorage.update(this.gameRef.id, {drawOffer: true});
288 abortGame: function() {
289 if (!confirm(this.st.tr["Terminate game?"]))
291 this.gameOver("?", "Abort");
292 this.people.forEach(p => {
293 if (p.sid != this.st.user.sid)
295 this.st.conn.send(JSON.stringify({
302 resign: function(e) {
303 if (!confirm("Resign the game?"))
305 this.people.forEach(p => {
306 if (p.sid != this.st.user.sid)
308 this.st.conn.send(JSON.stringify({code:"resign",
309 side:this.game.mycolor, target:p.sid}));
312 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
314 // 3 cases for loading a game:
315 // - from indexedDB (running or completed live game I play)
316 // - from server (one correspondance game I play[ed] or not)
317 // - from remote peer (one live game I don't play, finished or not)
318 loadGame: function(game, callback) {
319 const afterRetrieval = async (game) => {
320 const vModule = await import("@/variants/" + game.vname + ".js");
321 window.V = vModule.VariantRules;
322 this.vr = new V(game.fen);
323 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
324 const tc = extractTime(game.timeControl);
327 if (game.players[0].color == "b")
329 // Adopt the same convention for live and corr games: [0] = white
330 [ game.players[0], game.players[1] ] =
331 [ game.players[1], game.players[0] ];
333 // corr game: needs to compute the clocks + initime
334 // NOTE: clocks in seconds, initime in milliseconds
335 game.clocks = [tc.mainTime, tc.mainTime];
336 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
337 if (game.score == "*") //otherwise no need to bother with time
339 game.initime = [0, 0];
340 const L = game.moves.length;
343 let addTime = [0, 0];
344 for (let i=2; i<L; i++)
346 addTime[i%2] += tc.increment -
347 (game.moves[i].played - game.moves[i-1].played) / 1000;
349 for (let i=0; i<=1; i++)
350 game.clocks[i] += addTime[i];
353 game.initime[L%2] = game.moves[L-1].played;
355 this.drawOffer = "received";
357 // Now that we used idx and played, re-format moves as for live games
358 game.moves = game.moves.map( (m) => {
368 const myIdx = game.players.findIndex(p => {
369 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
371 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
373 game.clocks = [tc.mainTime, tc.mainTime];
374 if (game.score == "*")
376 game.initime[0] = Date.now();
379 // I play in this live game; corr games don't have clocks+initime
380 GameStorage.update(game.id,
383 initime: game.initime,
388 this.game = Object.assign({},
390 // NOTE: assign mycolor here, since BaseGame could also be VS computer
393 increment: tc.increment,
394 mycolor: [undefined,"w","b"][myIdx+1],
395 // opponent sid not strictly required (or available), but easier
396 // at least oppsid or oppid is available anyway:
397 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
398 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
401 this.repeat = {}; //reset
402 if (!!this.lastate) //lastate arrived before game was loaded:
403 this.processLastate();
407 return afterRetrieval(game);
408 if (!!this.gameRef.rid)
410 // Remote live game: forgetting about callback func... (TODO: design)
411 this.st.conn.send(JSON.stringify(
412 {code:"askfullgame", target:this.gameRef.rid}));
416 // Local or corr game
417 GameStorage.get(this.gameRef.id, afterRetrieval);
420 // Post-process a move (which was just played)
421 processMove: function(move) {
422 if (!this.game.mycolor)
423 return; //I'm just an observer
424 // Update storage (corr or live)
425 const colorIdx = ["w","b"].indexOf(move.color);
426 // https://stackoverflow.com/a/38750895
427 const allowed_fields = ["appear", "vanish", "start", "end"];
428 const filtered_move = Object.keys(move)
429 .filter(key => allowed_fields.includes(key))
430 .reduce((obj, key) => {
431 obj[key] = move[key];
434 // Send move ("newmove" event) to people in the room (if our turn)
436 if (move.color == this.game.mycolor)
438 if (this.game.moves.length >= 2) //after first move
440 const elapsed = Date.now() - this.game.initime[colorIdx];
441 // elapsed time is measured in milliseconds
442 addTime = this.game.increment - elapsed/1000;
444 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
445 this.people.forEach(p => {
446 if (p.sid != this.st.user.sid)
448 this.st.conn.send(JSON.stringify({
457 addTime = move.addTime; //supposed transmitted
458 const nextIdx = ["w","b"].indexOf(this.vr.turn);
459 // Since corr games are stored at only one location, update should be
460 // done only by one player for each move:
461 if (this.game.type == "live" || move.color == this.game.mycolor)
463 if (this.game.type == "corr")
465 GameStorage.update(this.gameRef.id,
470 squares: filtered_move,
471 played: Date.now(), //TODO: on server?
472 idx: this.game.moves.length,
478 GameStorage.update(this.gameRef.id,
482 clocks: this.game.clocks.map((t,i) => i==colorIdx
483 ? this.game.clocks[i] + addTime
484 : this.game.clocks[i]),
485 initime: this.game.initime.map((t,i) => i==nextIdx
487 : this.game.initime[i]),
491 // Also update current game object:
492 this.game.moves.push(move);
493 this.game.fen = move.fen;
494 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
495 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
496 this.game.initime[nextIdx] = Date.now();
497 // If repetition detected, consider that a draw offer was received:
498 const fenObj = V.ParseFen(move.fen);
499 let repIdx = fenObj.position + "_" + fenObj.turn;
501 repIdx += "_" + fenObj.flags;
502 this.repeat[repIdx] = (!!this.repeat[repIdx]
503 ? this.repeat[repIdx]+1
505 if (this.repeat[repIdx] >= 3)
506 this.drawOffer = "received"; //TODO: will print "mutual agreement"...
508 processChat: function(chat) {
509 if (this.game.type == "corr")
510 GameStorage.update(this.gameRef.id, {chat: chat});
512 gameOver: function(score, scoreMsg) {
513 this.game.mode = "analyze";
514 this.game.score = score;
515 this.game.scoreMsg = scoreMsg;
516 const myIdx = this.game.players.findIndex(p => {
517 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
519 if (myIdx >= 0) //OK, I play in this game
520 GameStorage.update(this.gameRef.id, { score: score });
528 background-color: green
530 background-color: red
532 @media screen and (min-width: 768px)
535 @media screen and (max-width: 767px)
544 display: inline-block