3 input#modalChat.modal(type="checkbox" @change="toggleChat")
4 div(role="dialog" aria-labelledby="inputChat")
6 label.modal-close(for="modalChat")
7 Chat(:players="game.players" :pastChats="game.chats"
8 @newchat-sent="finishSendChat" @newchat-received="processChat")
10 .col-sm-12.col-md-9.col-md-offset-3.col-lg-10.col-lg-offset-2
11 #actions(v-if="game.mode!='analyze' && game.score=='*'")
12 button(@click="offerDraw") Draw
13 button(@click="abortGame") Abort
14 button(@click="resign") Resign
15 button#chatBtn(onClick="doClick('modalChat')") Chat
16 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
17 div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
18 BaseGame(:game="game" :vr="vr" ref="basegame"
19 @newmove="processMove" @gameover="gameOver")
23 import BaseGame from "@/components/BaseGame.vue";
24 import Chat from "@/components/Chat.vue";
25 import { store } from "@/store";
26 import { GameStorage } from "@/utils/gameStorage";
27 import { ppt } from "@/utils/datetime";
28 import { extractTime } from "@/utils/timeControl";
29 import { ArrayFun } from "@/utils/array";
37 // gameRef: to find the game in (potentially remote) storage
41 gameRef: { //given in URL (rid = remote ID)
45 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
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.gameOver(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.$set(this.game, "moveToPlay", data.move); //TODO: Vue3...
204 case "lastate": //got opponent infos about last move
207 if (!!this.game.type) //game is loaded
208 this.processLastate();
209 //else: will be processed when game is ready
213 this.gameOver(data.side=="b" ? "1-0" : "0-1", "Resign");
216 this.gameOver("?", "Abort");
219 this.gameOver("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.$set(this.game, "moveToPlay", data.lastMove);
251 if (data.score != "*" && this.game.score == "*")
253 // Opponent resigned or aborted game, or accepted draw offer
254 // (this is not a stalemate or checkmate)
255 this.gameOver(data.score, "Opponent action");
257 this.game.clocks = data.clocks; //TODO: check this?
258 if (!!data.lastMove.draw)
259 this.drawOffer = "received";
262 offerDraw: function() {
263 if (["received","threerep"].includes(this.drawOffer))
265 if (!confirm("Accept draw?"))
267 this.people.forEach(p => {
268 if (p.sid != this.st.user.sid)
269 this.st.conn.send(JSON.stringify({code:"draw", target:p.sid}));
271 const message = (this.drawOffer == "received"
273 : "Three repetitions");
274 this.gameOver("1/2", message);
276 else if (this.drawOffer == "sent")
279 if (this.game.type == "corr")
280 GameStorage.update(this.gameRef.id, {drawOffer: false});
284 if (!confirm("Offer draw?"))
286 this.drawOffer = "sent";
287 this.people.forEach(p => {
288 if (p.sid != this.st.user.sid)
289 this.st.conn.send(JSON.stringify({code:"drawoffer", target:p.sid}));
291 if (this.game.type == "corr")
292 GameStorage.update(this.gameRef.id, {drawOffer: true});
295 abortGame: function() {
296 if (!confirm(this.st.tr["Terminate game?"]))
298 this.gameOver("?", "Abort");
299 this.people.forEach(p => {
300 if (p.sid != this.st.user.sid)
302 this.st.conn.send(JSON.stringify({
309 resign: function(e) {
310 if (!confirm("Resign the game?"))
312 this.people.forEach(p => {
313 if (p.sid != this.st.user.sid)
315 this.st.conn.send(JSON.stringify({code:"resign",
316 side:this.game.mycolor, target:p.sid}));
319 this.gameOver(this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
321 // 3 cases for loading a game:
322 // - from indexedDB (running or completed live game I play)
323 // - from server (one correspondance game I play[ed] or not)
324 // - from remote peer (one live game I don't play, finished or not)
325 loadGame: function(game, callback) {
326 const afterRetrieval = async (game) => {
327 const vModule = await import("@/variants/" + game.vname + ".js");
328 window.V = vModule.VariantRules;
329 this.vr = new V(game.fen);
330 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
331 const tc = extractTime(game.timeControl);
334 if (game.players[0].color == "b")
336 // Adopt the same convention for live and corr games: [0] = white
337 [ game.players[0], game.players[1] ] =
338 [ game.players[1], game.players[0] ];
340 // corr game: needs to compute the clocks + initime
341 // NOTE: clocks in seconds, initime in milliseconds
342 game.clocks = [tc.mainTime, tc.mainTime];
343 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
344 if (game.score == "*") //otherwise no need to bother with time
346 game.initime = [0, 0];
347 const L = game.moves.length;
350 let addTime = [0, 0];
351 for (let i=2; i<L; i++)
353 addTime[i%2] += tc.increment -
354 (game.moves[i].played - game.moves[i-1].played) / 1000;
356 for (let i=0; i<=1; i++)
357 game.clocks[i] += addTime[i];
360 game.initime[L%2] = game.moves[L-1].played;
362 this.drawOffer = "received";
364 // Now that we used idx and played, re-format moves as for live games
365 game.moves = game.moves.map( (m) => {
374 // Also sort chat messages (if any)
375 game.chats.sort( (c1,c2) => { return c2.added - c1.added; });
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 this.repeat = {}; //reset
411 if (!!this.lastate) //lastate arrived before game was loaded:
412 this.processLastate();
416 return afterRetrieval(game);
417 if (!!this.gameRef.rid)
419 // Remote live game: forgetting about callback func... (TODO: design)
420 this.st.conn.send(JSON.stringify(
421 {code:"askfullgame", target:this.gameRef.rid}));
425 // Local or corr game
426 GameStorage.get(this.gameRef.id, afterRetrieval);
429 // Post-process a move (which was just played)
430 processMove: function(move) {
431 // Update storage (corr or live) if I play in the game
432 const colorIdx = ["w","b"].indexOf(move.color);
433 // https://stackoverflow.com/a/38750895
434 if (!!this.game.mycolor)
436 const allowed_fields = ["appear", "vanish", "start", "end"];
437 // NOTE: 'var' to see this variable outside this block
438 var filtered_move = Object.keys(move)
439 .filter(key => allowed_fields.includes(key))
440 .reduce((obj, key) => {
441 obj[key] = move[key];
445 // Send move ("newmove" event) to people in the room (if our turn)
447 if (move.color == this.game.mycolor)
449 if (this.game.moves.length >= 2) //after first move
451 const elapsed = Date.now() - this.game.initime[colorIdx];
452 // elapsed time is measured in milliseconds
453 addTime = this.game.increment - elapsed/1000;
455 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
456 this.people.forEach(p => {
457 if (p.sid != this.st.user.sid)
459 this.st.conn.send(JSON.stringify({
468 addTime = move.addTime; //supposed transmitted
469 const nextIdx = ["w","b"].indexOf(this.vr.turn);
470 // Since corr games are stored at only one location, update should be
471 // done only by one player for each move:
472 if (!!this.game.mycolor &&
473 (this.game.type == "live" || move.color == this.game.mycolor))
475 if (this.game.type == "corr")
477 GameStorage.update(this.gameRef.id,
482 squares: filtered_move,
483 played: Date.now(), //TODO: on server?
484 idx: this.game.moves.length,
490 GameStorage.update(this.gameRef.id,
494 clocks: this.game.clocks.map((t,i) => i==colorIdx
495 ? this.game.clocks[i] + addTime
496 : this.game.clocks[i]),
497 initime: this.game.initime.map((t,i) => i==nextIdx
499 : this.game.initime[i]),
503 // Also update current game object:
504 this.game.moves.push(move);
505 this.game.fen = move.fen;
506 //TODO: (Vue3) just this.game.clocks[colorIdx] += addTime;
507 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
508 this.game.initime[nextIdx] = Date.now();
509 // If repetition detected, consider that a draw offer was received:
510 const fenObj = V.ParseFen(move.fen);
511 let repIdx = fenObj.position + "_" + fenObj.turn;
513 repIdx += "_" + fenObj.flags;
514 this.repeat[repIdx] = (!!this.repeat[repIdx]
515 ? this.repeat[repIdx]+1
517 if (this.repeat[repIdx] >= 3)
518 this.drawOffer = "threerep";
520 toggleChat: function() {
521 document.getElementById("chatBtn").style.backgroundColor = "#e2e2e2";
523 finishSendChat: function(chat) {
524 if (this.game.type == "corr")
525 GameStorage.update(this.gameRef.id, {chat: chat});
527 processChat: function() {
528 if (!document.getElementById("inputChat").checked)
529 document.getElementById("chatBtn").style.backgroundColor = "#c5fefe";
531 gameOver: function(score, scoreMsg) {
532 this.game.mode = "analyze";
533 this.game.score = score;
534 this.game.scoreMsg = scoreMsg;
535 const myIdx = this.game.players.findIndex(p => {
536 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
538 if (myIdx >= 0) //OK, I play in this game
539 GameStorage.update(this.gameRef.id, { score: score });
547 background-color: green
549 background-color: red
551 @media screen and (min-width: 768px)
554 @media screen and (max-width: 767px)
563 display: inline-block