3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
4 input#modalAbort.modal(type="checkbox")
5 div(role="dialog" aria-labelledby="abortBoxTitle")
6 .card.smallpad.small-modal.text-center
7 label.modal-close(for="modalAbort")
8 h3#abortBoxTitle.section {{ st.tr["Terminate game?"] }}
9 button(@click="abortGame") {{ st.tr["Sorry I have to go"] }}
10 button(@click="abortGame") {{ st.tr["Game seems over"] }}
11 button(@click="abortGame") {{ st.tr["Game is too boring"] }}
12 BaseGame(:game="game" :vr="vr" ref="basegame"
13 @newmove="processMove" @gameover="gameOver")
14 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
15 div(v-if="game.score=='*'") Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
16 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
17 button(@click="offerDraw") Draw
18 button(@click="() => abortGame()") Abort
19 button(@click="resign") Resign
20 textarea(v-if="game.score=='*'" v-model="corrMsg")
21 Chat(:players="game.players")
25 // ==> après, implémenter/vérifier les passages de challenges + parties en cours
30 import BaseGame from "@/components/BaseGame.vue";
31 import Chat from "@/components/Chat.vue";
32 import { store } from "@/store";
33 import { GameStorage } from "@/utils/gameStorage";
34 import { ppt } from "@/utils/datetime";
35 import { extractTime } from "@/utils/timeControl";
36 import { ArrayFun } from "@/utils/array";
44 // gameRef: to find the game in (potentially remote) storage
48 gameRef: { //given in URL (rid = remote ID)
52 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
53 corrMsg: "", //to send offline messages in corr games
54 virtualClocks: [0, 0], //initialized with true game.clocks
55 vr: null, //"variant rules" object initialized from FEN
56 drawOffer: "", //TODO: use for button style
57 people: [], //players + observers
61 "$route": function(to, from) {
62 this.gameRef.id = to.params["id"];
63 this.gameRef.rid = to.query["rid"];
66 "game.clocks": function(newState) {
67 if (this.game.moves.length < 2)
69 // 1st move not completed yet: freeze time
70 this.virtualClocks = newState.map(s => ppt(s));
73 const currentTurn = this.vr.turn;
74 const colorIdx = ["w","b"].indexOf(currentTurn);
75 let countdown = newState[colorIdx] -
76 (Date.now() - this.game.initime[colorIdx])/1000;
77 this.virtualClocks = [0,1].map(i => {
78 const removeTime = i == colorIdx
79 ? (Date.now() - this.game.initime[colorIdx])/1000
81 return ppt(newState[i] - removeTime);
83 let clockUpdate = setInterval(() => {
84 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
86 clearInterval(clockUpdate);
89 this.$refs["basegame"].endGame(
90 this.vr.turn=="w" ? "0-1" : "1-0", "Time");
95 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
96 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
101 // TODO: redundant code with Hall.vue (related to people array)
102 created: function() {
103 // Always add myself to players' list
104 const my = this.st.user;
105 this.people.push({sid:my.sid, id:my.id, name:my.name});
106 if (!!this.$route.params["id"])
108 this.gameRef.id = this.$route.params["id"];
109 this.gameRef.rid = this.$route.query["rid"];
112 // TODO: mode analyse (/analyze/Atomic/rn
113 // ... fen = query[], vname=params[] ...
114 // 0.1] Ask server for room composition:
115 const funcPollClients = () => {
116 this.st.conn.send(JSON.stringify({code:"pollclients"}));
118 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
120 else //socket not ready yet (initial loading)
121 this.st.conn.onopen = funcPollClients;
122 this.st.conn.onmessage = this.socketMessageListener;
123 const socketCloseListener = () => {
124 store.socketCloseListener(); //reinitialize connexion (in store.js)
125 this.st.conn.addEventListener('message', this.socketMessageListener);
126 this.st.conn.addEventListener('close', socketCloseListener);
128 this.st.conn.onclose = socketCloseListener;
131 getOppSid: function() {
132 if (!!this.game.oppsid)
133 return this.game.oppsid;
134 const opponent = this.people.find(p => p.id == this.game.oppid);
135 return (!!opponent ? opponent.sid : null);
137 socketMessageListener: function(msg) {
138 const data = JSON.parse(msg.data);
141 // 0.2] Receive clients list (just socket IDs)
144 data.sockIds.forEach(sid => {
145 this.people.push({sid:sid, id:0, name:""});
147 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
153 // Request for identification: reply if I'm not anonymous
154 if (this.st.user.id > 0)
156 this.st.conn.send(JSON.stringify(
157 // people[0] instead of st.user to avoid sending email
158 {code:"identity", user:this.people[0], target:data.from}));
164 let player = this.people.find(p => p.sid == data.user.sid);
165 // NOTE: sometimes player.id fails because player is undefined...
166 // Probably because the event was meant for Hall?
169 player.id = data.user.id;
170 player.name = data.user.name;
171 // Sending last state only for live games: corr games are complete
172 if (this.game.type == "live" && this.game.oppsid == player.sid)
174 // Send our "last state" informations to opponent
175 const L = this.game.moves.length;
176 this.st.conn.send(JSON.stringify({
181 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
182 score: this.game.score,
184 drawOffer: this.drawOffer,
185 clocks: this.game.clocks,
192 // Send current (live) game
195 // Minimal game informations:
197 players: this.game.players.map(p => p.name),
199 timeControl: this.game.timeControl,
201 this.st.conn.send(JSON.stringify({code:"game",
202 game:myGame, target:data.from}));
205 // NOTE: this call to play() will trigger processMove()
206 this.$refs["basegame"].play(data.move,
207 "receive", this.game.vname!="Dark" ? "animate" : null);
209 case "lastate": //got opponent infos about last move
211 const L = this.game.moves.length;
212 if (data.movesCount > L)
214 // Just got last move from him
215 this.$refs["basegame"].play(data.lastMove,
216 "receive", this.game.vname!="Dark" ? "animate" : null);
217 if (data.score != "*" && this.game.score == "*")
219 // Opponent resigned or aborted game, or accepted draw offer
220 // (this is not a stalemate or checkmate)
221 this.$refs["basegame"].endGame(data.score, "Opponent action");
223 this.game.clocks = data.clocks; //TODO: check this?
224 this.drawOffer = data.drawOffer; //does opponent offer draw?
229 this.$refs["basegame"].endGame(
230 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
233 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
236 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
239 this.drawOffer = "received";
242 // TODO: just give game; observers are listed here anyway:
243 // ==> mark request SID as someone to send moves to
244 // NOT to all people array: our opponent can send moves too!
247 // and when receiving answer just call loadGame(received_game)
248 this.loadGame(data.game);
250 // TODO: drawaccepted (click draw button before sending move
251 // ==> draw offer in move)
252 // ==> on "newmove", check "drawOffer" field
255 this.people.push({name:"", id:0, sid:data.from});
256 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.from}));
260 ArrayFun.remove(this.people, p => p.sid == data.from);
264 offerDraw: function() {
265 // TODO: also for corr games
266 if (this.drawOffer == "received")
268 if (!confirm("Accept draw?"))
270 const oppsid = this.getOppSid();
272 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
273 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
275 else if (this.drawOffer == "sent")
279 if (!confirm("Offer draw?"))
281 const oppsid = this.getOppSid();
283 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
286 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
287 receiveDrawOffer: function() {
289 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
290 // if accept: send message "draw"
292 abortGame: function(event) {
293 let modalBox = document.getElementById("modalAbort");
296 // First call show options:
297 modalBox.checked = true;
301 modalBox.checked = false; //decision made: box disappear
302 const message = event.target.innerText;
303 // Next line will trigger a "gameover" event, bubbling up till here
304 this.$refs["basegame"].endGame("?", "Abort: " + message);
305 const oppsid = this.getOppSid();
308 this.st.conn.send(JSON.stringify({
316 resign: function(e) {
317 if (!confirm("Resign the game?"))
319 const oppsid = this.getOppSid();
322 this.st.conn.send(JSON.stringify({
327 // Next line will trigger a "gameover" event, bubbling up till here
328 this.$refs["basegame"].endGame(
329 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
331 // 3 cases for loading a game:
332 // - from indexedDB (running or completed live game I play)
333 // - from server (one correspondance game I play[ed] or not)
334 // - from remote peer (one live game I don't play, finished or not)
335 loadGame: function(game) {
336 const afterRetrieval = async (game) => {
337 const vModule = await import("@/variants/" + game.vname + ".js");
338 window.V = vModule.VariantRules;
339 this.vr = new V(game.fen);
340 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
341 const tc = extractTime(game.timeControl);
344 if (game.players[0].color == "b")
346 // Adopt the same convention for live and corr games: [0] = white
347 [ game.players[0], game.players[1] ] =
348 [ game.players[1], game.players[0] ];
350 // corr game: needs to compute the clocks + initime
351 game.clocks = [tc.mainTime, tc.mainTime];
352 game.initime = [0, 0];
353 const L = game.moves.length;
354 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
357 let addTime = [0, 0];
358 for (let i=2; i<L; i++)
360 addTime[i%2] += tc.increment -
361 (game.moves[i].played - game.moves[i-1].played);
363 for (let i=0; i<=1; i++)
364 game.clocks[i] += addTime[i];
367 game.initime[L%2] = game.moves[L-1].played;
368 // Now that we used idx and played, re-format moves as for live games
369 game.moves = game.moves.map( (m) => {
380 const myIdx = game.players.findIndex(p => {
381 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
383 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
385 game.clocks = [tc.mainTime, tc.mainTime];
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,
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),
412 return afterRetrival(game);
413 if (!!this.gameRef.rid)
416 this.st.conn.send(JSON.stringify(
417 {code:"askfullgame", target:this.gameRef.rid}));
418 // (send moves updates + resign/abort/draw actions)
422 // Local or corr game
423 GameStorage.get(this.gameRef.id, afterRetrieval);
426 // Post-process a move (which was just played)
427 processMove: function(move) {
428 if (!this.game.mycolor)
429 return; //I'm just an observer
430 // Update storage (corr or live)
431 const colorIdx = ["w","b"].indexOf(move.color);
432 // https://stackoverflow.com/a/38750895
433 const allowed_fields = ["appear", "vanish", "start", "end"];
434 const filtered_move = Object.keys(move)
435 .filter(key => allowed_fields.includes(key))
436 .reduce((obj, key) => {
437 obj[key] = move[key];
440 // Send move ("newmove" event) to opponent(s) (if ours)
442 if (move.color == this.game.mycolor)
444 if (this.game.moves.length >= 2) //after first move
446 const elapsed = Date.now() - this.game.initime[colorIdx];
447 // elapsed time is measured in milliseconds
448 addTime = this.game.increment - elapsed/1000;
450 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
451 if (this.game.type == "corr")
452 sendMove.message = this.corrMsg;
453 const oppsid = this.getOppSid();
456 this.st.conn.send(JSON.stringify({
462 if (this.game.type == "corr" && this.corrMsg != "")
464 // Add message to last move in BaseGame:
465 // TODO: not very good style...
466 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
470 addTime = move.addTime; //supposed transmitted
471 const nextIdx = ["w","b"].indexOf(this.vr.turn);
472 // Since corr games are stored at only one location, update should be
473 // done only by one player for each move:
474 if (this.game.type == "live" || move.color == this.game.mycolor)
476 if (this.game.type == "corr")
478 GameStorage.update(this.gameRef.id,
483 squares: filtered_move,
484 message: this.corrMsg,
485 played: Date.now(), //TODO: on server?
486 idx: this.game.moves.length,
492 GameStorage.update(this.gameRef.id,
496 clocks: this.game.clocks.map((t,i) => i==colorIdx
497 ? this.game.clocks[i] + addTime
498 : this.game.clocks[i]),
499 initime: this.game.initime.map((t,i) => i==nextIdx
501 : this.game.initime[i]),
505 // Also update current game object:
506 this.game.moves.push(move);
507 this.game.fen = move.fen;
508 //TODO: just this.game.clocks[colorIdx] += addTime;
509 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
510 this.game.initime[nextIdx] = Date.now();
511 // Finally reset curMoveMessage if needed
512 if (this.game.type == "corr" && move.color == this.game.mycolor)
515 gameOver: function(score) {
516 this.game.mode = "analyze";
517 this.game.score = score;
518 GameStorage.update(this.gameRef.id, { score: score });