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")
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 { store } from "@/store";
34 import { GameStorage } from "@/utils/gameStorage";
35 import { ppt } from "@/utils/datetime";
36 import { extractTime } from "@/utils/timeControl";
37 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 player.id = data.user.id;
166 player.name = data.user.name;
167 // Sending last state only for live games: corr games are complete
168 if (this.game.type == "live" && this.game.oppsid == player.sid)
170 // Send our "last state" informations to opponent
171 const L = this.game.moves.length;
172 this.st.conn.send(JSON.stringify({
177 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
178 score: this.game.score,
180 drawOffer: this.drawOffer,
181 clocks: this.game.clocks,
188 // NOTE: this call to play() will trigger processMove()
189 this.$refs["basegame"].play(data.move,
190 "receive", this.game.vname!="Dark" ? "animate" : null);
192 case "lastate": //got opponent infos about last move
194 const L = this.game.moves.length;
195 if (data.movesCount > L)
197 // Just got last move from him
198 this.$refs["basegame"].play(data.lastMove,
199 "receive", this.game.vname!="Dark" ? "animate" : null);
200 if (data.score != "*" && this.game.score == "*")
202 // Opponent resigned or aborted game, or accepted draw offer
203 // (this is not a stalemate or checkmate)
204 this.$refs["basegame"].endGame(data.score, "Opponent action");
206 this.game.clocks = data.clocks; //TODO: check this?
207 this.drawOffer = data.drawOffer; //does opponent offer draw?
212 this.$refs["basegame"].endGame(
213 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
216 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
219 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
222 this.drawOffer = "received";
225 // TODO: just give game; observers are listed here anyway:
226 // ==> mark request SID as someone to send moves to
227 // NOT to all people array: our opponent can send moves too!
230 // and when receiving answer just call loadGame(received_game)
231 this.loadGame(data.game);
233 // TODO: drawaccepted (click draw button before sending move
234 // ==> draw offer in move)
235 // ==> on "newmove", check "drawOffer" field
238 this.people.push({name:"", id:0, sid:data.sid});
239 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
243 ArrayFun.remove(this.people, p => p.sid == data.sid);
247 offerDraw: function() {
248 // TODO: also for corr games
249 if (this.drawOffer == "received")
251 if (!confirm("Accept draw?"))
253 const oppsid = this.getOppSid();
255 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
256 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
258 else if (this.drawOffer == "sent")
262 if (!confirm("Offer draw?"))
264 const oppsid = this.getOppSid();
266 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
269 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
270 receiveDrawOffer: function() {
272 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
273 // if accept: send message "draw"
275 abortGame: function(event) {
276 let modalBox = document.getElementById("modalAbort");
279 // First call show options:
280 modalBox.checked = true;
284 modalBox.checked = false; //decision made: box disappear
285 const message = event.target.innerText;
286 // Next line will trigger a "gameover" event, bubbling up till here
287 this.$refs["basegame"].endGame("?", "Abort: " + message);
288 const oppsid = this.getOppSid();
291 this.st.conn.send(JSON.stringify({
299 resign: function(e) {
300 if (!confirm("Resign the game?"))
302 const oppsid = this.getOppSid();
305 this.st.conn.send(JSON.stringify({
310 // Next line will trigger a "gameover" event, bubbling up till here
311 this.$refs["basegame"].endGame(
312 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) {
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 game.clocks = [tc.mainTime, tc.mainTime];
335 game.initime = [0, 0];
336 const L = game.moves.length;
337 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
340 let addTime = [0, 0];
341 for (let i=2; i<L; i++)
343 addTime[i%2] += tc.increment -
344 (game.moves[i].played - game.moves[i-1].played);
346 for (let i=0; i<=1; i++)
347 game.clocks[i] += addTime[i];
350 game.initime[L%2] = game.moves[L-1].played;
351 // Now that we used idx and played, re-format moves as for live games
352 game.moves = game.moves.map( (m) => {
363 const myIdx = game.players.findIndex(p => {
364 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
366 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
368 game.clocks = [tc.mainTime, tc.mainTime];
369 game.initime[0] = Date.now();
372 // I play in this live game; corr games don't have clocks+initime
373 GameStorage.update(game.id,
376 initime: game.initime,
380 this.game = Object.assign({},
382 // NOTE: assign mycolor here, since BaseGame could also be VS computer
385 increment: tc.increment,
386 mycolor: [undefined,"w","b"][myIdx+1],
387 // opponent sid not strictly required (or available), but easier
388 // at least oppsid or oppid is available anyway:
389 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
390 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
395 return afterRetrival(game);
396 if (!!this.gameRef.rid)
399 this.st.conn.send(JSON.stringify(
400 {code:"askfullgame", target:this.gameRef.rid}));
401 // (send moves updates + resign/abort/draw actions)
405 // Local or corr game
406 GameStorage.get(this.gameRef.id, afterRetrieval);
409 // Post-process a move (which was just played)
410 processMove: function(move) {
411 if (!this.game.mycolor)
412 return; //I'm just an observer
413 // Update storage (corr or live)
414 const colorIdx = ["w","b"].indexOf(move.color);
415 // https://stackoverflow.com/a/38750895
416 const allowed_fields = ["appear", "vanish", "start", "end"];
417 const filtered_move = Object.keys(move)
418 .filter(key => allowed_fields.includes(key))
419 .reduce((obj, key) => {
420 obj[key] = move[key];
423 // Send move ("newmove" event) to opponent(s) (if ours)
425 if (move.color == this.game.mycolor)
427 if (this.game.moves.length >= 2) //after first move
429 const elapsed = Date.now() - this.game.initime[colorIdx];
430 // elapsed time is measured in milliseconds
431 addTime = this.game.increment - elapsed/1000;
433 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
434 if (this.game.type == "corr")
435 sendMove.message = this.corrMsg;
436 const oppsid = this.getOppSid();
439 this.st.conn.send(JSON.stringify({
445 if (this.game.type == "corr" && this.corrMsg != "")
447 // Add message to last move in BaseGame:
448 // TODO: not very good style...
449 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
453 addTime = move.addTime; //supposed transmitted
454 const nextIdx = ["w","b"].indexOf(this.vr.turn);
455 // Since corr games are stored at only one location, update should be
456 // done only by one player for each move:
457 if (this.game.type == "live" || move.color == this.game.mycolor)
459 if (this.game.type == "corr")
461 GameStorage.update(this.gameRef.id,
466 squares: filtered_move,
467 message: this.corrMsg,
468 played: Date.now(), //TODO: on server?
469 idx: this.game.moves.length,
475 GameStorage.update(this.gameRef.id,
479 clocks: this.game.clocks.map((t,i) => i==colorIdx
480 ? this.game.clocks[i] + addTime
481 : this.game.clocks[i]),
482 initime: this.game.initime.map((t,i) => i==nextIdx
484 : this.game.initime[i]),
488 // Also update current game object:
489 this.game.moves.push(move);
490 this.game.fen = move.fen;
491 //TODO: just this.game.clocks[colorIdx] += addTime;
492 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
493 this.game.initime[nextIdx] = Date.now();
494 // Finally reset curMoveMessage if needed
495 if (this.game.type == "corr" && move.color == this.game.mycolor)
498 gameOver: function(score) {
499 this.game.mode = "analyze";
500 this.game.score = score;
501 GameStorage.update(this.gameRef.id, { score: score });