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")
24 // TODO: movelist dans basegame et chat ici
25 // ==> après, implémenter/vérifier les passages de challenges + parties en cours
27 // when send to chat (or a move), reach only this group (send gid along)
31 import BaseGame from "@/components/BaseGame.vue";
32 //import Chat from "@/components/Chat.vue";
33 //import MoveList from "@/components/MoveList.vue";
34 import { store } from "@/store";
35 import { GameStorage } from "@/utils/gameStorage";
36 import { ppt } from "@/utils/datetime";
37 import { extractTime } from "@/utils/timeControl";
38 import { ArrayFun } from "@/utils/array";
45 // gameRef: to find the game in (potentially remote) storage
49 gameRef: { //given in URL (rid = remote ID)
53 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
54 corrMsg: "", //to send offline messages in corr games
55 virtualClocks: [0, 0], //initialized with true game.clocks
56 vr: null, //"variant rules" object initialized from FEN
57 drawOffer: "", //TODO: use for button style
58 people: [], //players + observers
62 "$route": function(to, from) {
63 this.gameRef.id = to.params["id"];
64 this.gameRef.rid = to.query["rid"];
67 "game.clocks": function(newState) {
68 if (this.game.moves.length < 2)
70 // 1st move not completed yet: freeze time
71 this.virtualClocks = newState.map(s => ppt(s));
74 const currentTurn = this.vr.turn;
75 const colorIdx = ["w","b"].indexOf(currentTurn);
76 let countdown = newState[colorIdx] -
77 (Date.now() - this.game.initime[colorIdx])/1000;
78 this.virtualClocks = [0,1].map(i => {
79 const removeTime = i == colorIdx
80 ? (Date.now() - this.game.initime[colorIdx])/1000
82 return ppt(newState[i] - removeTime);
84 let clockUpdate = setInterval(() => {
85 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
87 clearInterval(clockUpdate);
90 this.$refs["basegame"].endGame(
91 this.vr.turn=="w" ? "0-1" : "1-0", "Time");
96 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
97 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
102 // TODO: redundant code with Hall.vue (related to people array)
103 created: function() {
104 // Always add myself to players' list
105 const my = this.st.user;
106 this.people.push({sid:my.sid, id:my.id, name:my.name});
107 if (!!this.$route.params["id"])
109 this.gameRef.id = this.$route.params["id"];
110 this.gameRef.rid = this.$route.query["rid"];
113 // TODO: mode analyse (/analyze/Atomic/rn
114 // ... fen = query[], vname=params[] ...
115 // 0.1] Ask server for room composition:
116 const funcPollClients = () => {
117 this.st.conn.send(JSON.stringify({code:"pollclients"}));
119 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
121 else //socket not ready yet (initial loading)
122 this.st.conn.onopen = funcPollClients;
123 this.st.conn.onmessage = this.socketMessageListener;
124 const socketCloseListener = () => {
125 store.socketCloseListener(); //reinitialize connexion (in store.js)
126 this.st.conn.addEventListener('message', this.socketMessageListener);
127 this.st.conn.addEventListener('close', socketCloseListener);
129 this.st.conn.onclose = socketCloseListener;
132 getOppSid: function() {
133 if (!!this.game.oppsid)
134 return this.game.oppsid;
135 const opponent = this.people.find(p => p.id == this.game.oppid);
136 return (!!opponent ? opponent.sid : null);
138 socketMessageListener: function(msg) {
139 const data = JSON.parse(msg.data);
142 // 0.2] Receive clients list (just socket IDs)
145 data.sockIds.forEach(sid => {
146 this.people.push({sid:sid, id:0, name:""});
148 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
154 // Request for identification: reply if I'm not anonymous
155 if (this.st.user.id > 0)
157 this.st.conn.send(JSON.stringify(
158 // people[0] instead of st.user to avoid sending email
159 {code:"identity", user:this.people[0], target:data.from}));
165 let player = this.people.find(p => p.sid == data.user.sid);
166 player.id = data.user.id;
167 player.name = data.user.name;
168 // Sending last state only for live games: corr games are complete
169 if (this.game.type == "live" && this.game.oppsid == player.sid)
171 // Send our "last state" informations to opponent
172 const L = this.game.moves.length;
173 this.st.conn.send(JSON.stringify({
178 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
179 score: this.game.score,
181 drawOffer: this.drawOffer,
182 clocks: this.game.clocks,
189 // NOTE: this call to play() will trigger processMove()
190 this.$refs["basegame"].play(data.move,
191 "receive", this.game.vname!="Dark" ? "animate" : null);
193 case "lastate": //got opponent infos about last move
195 const L = this.game.moves.length;
196 if (data.movesCount > L)
198 // Just got last move from him
199 this.$refs["basegame"].play(data.lastMove,
200 "receive", this.game.vname!="Dark" ? "animate" : null);
201 if (data.score != "*" && this.game.score == "*")
203 // Opponent resigned or aborted game, or accepted draw offer
204 // (this is not a stalemate or checkmate)
205 this.$refs["basegame"].endGame(data.score, "Opponent action");
207 this.game.clocks = data.clocks; //TODO: check this?
208 this.drawOffer = data.drawOffer; //does opponent offer draw?
213 this.$refs["basegame"].endGame(
214 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
217 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
220 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
223 this.drawOffer = "received";
226 // TODO: just give game; observers are listed here anyway:
227 // ==> mark request SID as someone to send moves to
228 // NOT to all people array: our opponent can send moves too!
231 // and when receiving answer just call loadGame(received_game)
232 this.loadGame(data.game);
234 // TODO: drawaccepted (click draw button before sending move
235 // ==> draw offer in move)
236 // ==> on "newmove", check "drawOffer" field
239 this.people.push({name:"", id:0, sid:data.sid});
240 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
244 ArrayFun.remove(this.people, p => p.sid == data.sid);
248 offerDraw: function() {
249 // TODO: also for corr games
250 if (this.drawOffer == "received")
252 if (!confirm("Accept draw?"))
254 const oppsid = this.getOppSid();
256 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
257 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
259 else if (this.drawOffer == "sent")
263 if (!confirm("Offer draw?"))
265 const oppsid = this.getOppSid();
267 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
270 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
271 receiveDrawOffer: function() {
273 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
274 // if accept: send message "draw"
276 abortGame: function(event) {
277 let modalBox = document.getElementById("modalAbort");
280 // First call show options:
281 modalBox.checked = true;
285 modalBox.checked = false; //decision made: box disappear
286 const message = event.target.innerText;
287 // Next line will trigger a "gameover" event, bubbling up till here
288 this.$refs["basegame"].endGame("?", "Abort: " + message);
289 const oppsid = this.getOppSid();
292 this.st.conn.send(JSON.stringify({
300 resign: function(e) {
301 if (!confirm("Resign the game?"))
303 const oppsid = this.getOppSid();
306 this.st.conn.send(JSON.stringify({
311 // Next line will trigger a "gameover" event, bubbling up till here
312 this.$refs["basegame"].endGame(
313 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) {
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 game.clocks = [tc.mainTime, tc.mainTime];
336 game.initime = [0, 0];
337 const L = game.moves.length;
338 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
341 let addTime = [0, 0];
342 for (let i=2; i<L; i++)
344 addTime[i%2] += tc.increment -
345 (game.moves[i].played - game.moves[i-1].played);
347 for (let i=0; i<=1; i++)
348 game.clocks[i] += addTime[i];
351 game.initime[L%2] = game.moves[L-1].played;
352 // Now that we used idx and played, re-format moves as for live games
353 game.moves = game.moves.map( (m) => {
364 const myIdx = game.players.findIndex(p => {
365 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
367 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
369 game.clocks = [tc.mainTime, tc.mainTime];
370 game.initime[0] = Date.now();
373 // I play in this live game; corr games don't have clocks+initime
374 GameStorage.update(game.id,
377 initime: game.initime,
381 this.game = Object.assign({},
383 // NOTE: assign mycolor here, since BaseGame could also be VS computer
386 increment: tc.increment,
387 mycolor: [undefined,"w","b"][myIdx+1],
388 // opponent sid not strictly required (or available), but easier
389 // at least oppsid or oppid is available anyway:
390 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
391 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
396 return afterRetrival(game);
397 if (!!this.gameRef.rid)
400 this.st.conn.send(JSON.stringify(
401 {code:"askfullgame", target:this.gameRef.rid}));
402 // (send moves updates + resign/abort/draw actions)
406 // Local or corr game
407 GameStorage.get(this.gameRef.id, afterRetrieval);
410 // Post-process a move (which was just played)
411 processMove: function(move) {
412 if (!this.game.mycolor)
413 return; //I'm just an observer
414 // Update storage (corr or live)
415 const colorIdx = ["w","b"].indexOf(move.color);
416 // https://stackoverflow.com/a/38750895
417 const allowed_fields = ["appear", "vanish", "start", "end"];
418 const filtered_move = Object.keys(move)
419 .filter(key => allowed_fields.includes(key))
420 .reduce((obj, key) => {
421 obj[key] = move[key];
424 // Send move ("newmove" event) to opponent(s) (if ours)
426 if (move.color == this.game.mycolor)
428 if (this.game.moves.length >= 2) //after first move
430 const elapsed = Date.now() - this.game.initime[colorIdx];
431 // elapsed time is measured in milliseconds
432 addTime = this.game.increment - elapsed/1000;
434 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
435 if (this.game.type == "corr")
436 sendMove.message = this.corrMsg;
437 const oppsid = this.getOppSid();
440 this.st.conn.send(JSON.stringify({
446 if (this.game.type == "corr" && this.corrMsg != "")
448 // Add message to last move in BaseGame:
449 // TODO: not very good style...
450 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
454 addTime = move.addTime; //supposed transmitted
455 const nextIdx = ["w","b"].indexOf(this.vr.turn);
456 // Since corr games are stored at only one location, update should be
457 // done only by one player for each move:
458 if (this.game.type == "live" || move.color == this.game.mycolor)
460 if (this.game.type == "corr")
462 GameStorage.update(this.gameRef.id,
467 squares: filtered_move,
468 message: this.corrMsg,
469 played: Date.now(), //TODO: on server?
470 idx: this.game.moves.length,
476 GameStorage.update(this.gameRef.id,
480 clocks: this.game.clocks.map((t,i) => i==colorIdx
481 ? this.game.clocks[i] + addTime
482 : this.game.clocks[i]),
483 initime: this.game.initime.map((t,i) => i==nextIdx
485 : this.game.initime[i]),
489 // Also update current game object:
490 this.game.moves.push(move);
491 this.game.fen = move.fen;
492 //TODO: just this.game.clocks[colorIdx] += addTime;
493 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
494 this.game.initime[nextIdx] = Date.now();
495 // Finally reset curMoveMessage if needed
496 if (this.game.type == "corr" && move.color == this.game.mycolor)
499 gameOver: function(score) {
500 this.game.mode = "analyze";
501 this.game.score = score;
502 GameStorage.update(this.gameRef.id, { score: score });