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 textarea#mvMessage(v-if="game.type=='corr'" v-model="corrMsg")
15 div Names: {{ game.players[0].name }} - {{ game.players[1].name }}
16 div Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
17 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
18 button(@click="offerDraw") Draw
19 button(@click="() => abortGame()") Abort
20 button(@click="resign") Resign
21 div(v-if="game.mode=='corr'")
22 textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg")
23 div(v-show="cursor>=0") {{ moves[cursor].message }}
27 // TODO: movelist dans basegame et chat ici
28 // ==> après, implémenter/vérifier les passages de challenges + parties en cours
30 // + problèmes, habiller et publier. (+ corr...)
31 // when send to chat (or a move), reach only this group (send gid along)
35 import BaseGame from "@/components/BaseGame.vue";
36 //import Chat from "@/components/Chat.vue";
37 //import MoveList from "@/components/MoveList.vue";
38 import { store } from "@/store";
39 import { GameStorage } from "@/utils/gameStorage";
40 import { ppt } from "@/utils/datetime";
41 import { extractTime } from "@/utils/timeControl";
42 import { ArrayFun } from "@/utils/array";
49 // gameRef: to find the game in (potentially remote) storage
53 gameRef: { //given in URL (rid = remote ID)
57 game: {players:[{name:""},{name:""}]}, //passed to BaseGame
58 corrMsg: "", //to send offline messages in corr games
59 virtualClocks: [0, 0], //initialized with true game.clocks
60 vr: null, //"variant rules" object initialized from FEN
61 drawOffer: "", //TODO: use for button style
62 people: [], //players + observers
66 "$route": function(to, from) {
67 this.gameRef.id = to.params["id"];
68 this.gameRef.rid = to.query["rid"];
71 "game.clocks": function(newState) {
72 if (this.game.moves.length < 2)
74 // 1st move not completed yet: freeze time
75 this.virtualClocks = newState.map(s => ppt(s));
78 const currentTurn = this.vr.turn;
79 const colorIdx = ["w","b"].indexOf(currentTurn);
80 let countdown = newState[colorIdx] -
81 (Date.now() - this.game.initime[colorIdx])/1000;
82 this.virtualClocks = [0,1].map(i => {
83 const removeTime = i == colorIdx
84 ? (Date.now() - this.game.initime[colorIdx])/1000
86 return ppt(newState[i] - removeTime);
88 const myTurn = (currentTurn == this.game.mycolor);
89 let clockUpdate = setInterval(() => {
90 if (countdown <= 0 || this.vr.turn != currentTurn || this.game.score != "*")
92 clearInterval(clockUpdate);
93 if (countdown <= 0 && myTurn)
95 this.$refs["basegame"].endGame(
96 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
97 const oppsid = this.getOppSid();
100 this.st.conn.send(JSON.stringify({
109 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
110 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
115 // TODO: redundant code with Hall.vue (related to people array)
116 created: function() {
117 // Always add myself to players' list
118 const my = this.st.user;
119 this.people.push({sid:my.sid, id:my.id, name:my.name});
120 if (!!this.$route.params["id"])
122 this.gameRef.id = this.$route.params["id"];
123 this.gameRef.rid = this.$route.query["rid"];
126 // 0.1] Ask server for room composition:
127 const funcPollClients = () => {
128 this.st.conn.send(JSON.stringify({code:"pollclients"}));
130 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
132 else //socket not ready yet (initial loading)
133 this.st.conn.onopen = funcPollClients;
134 this.st.conn.onmessage = this.socketMessageListener;
135 const socketCloseListener = () => {
136 store.socketCloseListener(); //reinitialize connexion (in store.js)
137 this.st.conn.addEventListener('message', this.socketMessageListener);
138 this.st.conn.addEventListener('close', socketCloseListener);
140 this.st.conn.onclose = socketCloseListener;
143 getOppSid: function() {
144 if (!!this.game.oppsid)
145 return this.game.oppsid;
146 const opponent = this.people.find(p => p.id == this.game.oppid);
147 return (!!opponent ? opponent.sid : null);
149 socketMessageListener: function(msg) {
150 const data = JSON.parse(msg.data);
153 // 0.2] Receive clients list (just socket IDs)
156 data.sockIds.forEach(sid => {
157 this.people.push({sid:sid, id:0, name:""});
159 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
165 // Request for identification: reply if I'm not anonymous
166 if (this.st.user.id > 0)
168 this.st.conn.send(JSON.stringify(
169 // people[0] instead of st.user to avoid sending email
170 {code:"identity", user:this.people[0], target:data.from}));
176 let player = this.people.find(p => p.sid == data.user.sid);
177 player.id = data.user.id;
178 player.name = data.user.name;
179 // Sending last state only for live games: corr games are complete
180 if (this.game.type == "live" && this.game.oppsid == player.sid)
182 // Send our "last state" informations to opponent
183 const L = this.game.moves.length;
184 this.st.conn.send(JSON.stringify({
189 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
190 score: this.game.score,
192 drawOffer: this.drawOffer,
193 clocks: this.game.clocks,
200 // NOTE: this call to play() will trigger processMove()
201 this.$refs["basegame"].play(data.move,
202 "receive", this.game.vname!="Dark" ? "animate" : null);
204 case "lastate": //got opponent infos about last move
206 const L = this.game.moves.length;
207 if (data.movesCount > L)
209 // Just got last move from him
210 this.$refs["basegame"].play(data.lastMove,
211 "receive", this.game.vname!="Dark" ? "animate" : null);
212 if (data.score != "*" && this.game.score == "*")
214 // Opponent resigned or aborted game, or accepted draw offer
215 // (this is not a stalemate or checkmate)
216 this.$refs["basegame"].endGame(data.score, "Opponent action");
218 this.game.clocks = data.clocks; //TODO: check this?
219 this.drawOffer = data.drawOffer; //does opponent offer draw?
224 this.$refs["basegame"].endGame(
225 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
228 this.$refs["basegame"].endGame(
229 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
232 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
235 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
238 this.drawOffer = "received";
241 // TODO: just give game; observers are listed here anyway:
242 // ==> mark request SID as someone to send moves to
243 // NOT to all people array: our opponent can send moves too!
246 // and when receiving answer just call loadGame(received_game)
247 this.loadGame(data.game);
249 // TODO: drawaccepted (click draw button before sending move
250 // ==> draw offer in move)
251 // ==> on "newmove", check "drawOffer" field
254 this.people.push({name:"", id:0, sid:data.sid});
255 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
259 ArrayFun.remove(this.people, p => p.sid == data.sid);
263 offerDraw: function() {
264 // TODO: also for corr games
265 if (this.drawOffer == "received")
267 if (!confirm("Accept draw?"))
269 const oppsid = this.getOppSid();
271 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
272 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
274 else if (this.drawOffer == "sent")
278 if (!confirm("Offer draw?"))
280 const oppsid = this.getOppSid();
282 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
285 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
286 receiveDrawOffer: function() {
288 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
289 // if accept: send message "draw"
291 abortGame: function(event) {
292 let modalBox = document.getElementById("modalAbort");
295 // First call show options:
296 modalBox.checked = true;
300 modalBox.checked = false; //decision made: box disappear
301 const message = event.target.innerText;
302 // Next line will trigger a "gameover" event, bubbling up till here
303 this.$refs["basegame"].endGame("?", "Abort: " + message);
304 const oppsid = this.getOppSid();
307 this.st.conn.send(JSON.stringify({
315 resign: function(e) {
316 if (!confirm("Resign the game?"))
318 const oppsid = this.getOppSid();
321 this.st.conn.send(JSON.stringify({
326 // Next line will trigger a "gameover" event, bubbling up till here
327 this.$refs["basegame"].endGame(
328 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
330 // 3 cases for loading a game:
331 // - from indexedDB (running or completed live game I play)
332 // - from server (one correspondance game I play[ed] or not)
333 // - from remote peer (one live game I don't play, finished or not)
334 loadGame: function(game) {
335 const afterRetrieval = async (game) => {
336 const vModule = await import("@/variants/" + game.vname + ".js");
337 window.V = vModule.VariantRules;
338 this.vr = new V(game.fen);
339 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
340 const tc = extractTime(game.timeControl);
343 if (game.players[0].color == "b")
345 // Adopt the same convention for live and corr games: [0] = white
346 [ game.players[0], game.players[1] ] =
347 [ game.players[1], game.players[0] ];
349 // corr game: needs to compute the clocks + initime
350 game.clocks = [tc.mainTime, tc.mainTime];
351 game.initime = [0, 0];
352 const L = game.moves.length;
353 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
356 let addTime = [0, 0];
357 for (let i=2; i<L; i++)
359 addTime[i%2] += tc.increment -
360 (game.moves[i].played - game.moves[i-1].played);
362 for (let i=0; i<=1; i++)
363 game.clocks[i] += addTime[i];
366 game.initime[L%2] = game.moves[L-1].played;
367 // Now that we used idx and played, re-format moves as for live games
368 game.moves = game.moves.map( (m) => {
379 const myIdx = game.players.findIndex(p => {
380 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
382 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
384 game.clocks = [tc.mainTime, tc.mainTime];
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,
396 this.game = Object.assign({},
398 // NOTE: assign mycolor here, since BaseGame could also be VS computer
401 increment: tc.increment,
402 mycolor: [undefined,"w","b"][myIdx+1],
403 // opponent sid not strictly required (or available), but easier
404 // at least oppsid or oppid is available anyway:
405 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
406 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
411 return afterRetrival(game);
412 if (!!this.gameRef.rid)
415 this.st.conn.send(JSON.stringify(
416 {code:"askfullgame", target:this.gameRef.rid}));
417 // (send moves updates + resign/abort/draw actions)
421 // Local or corr game
422 GameStorage.get(this.gameRef.id, afterRetrieval);
425 // Post-process a move (which was just played)
426 processMove: function(move) {
427 if (!this.game.mycolor)
428 return; //I'm just an observer
429 // Update storage (corr or live)
430 const colorIdx = ["w","b"].indexOf(move.color);
431 // https://stackoverflow.com/a/38750895
432 const allowed_fields = ["appear", "vanish", "start", "end"];
433 const filtered_move = Object.keys(move)
434 .filter(key => allowed_fields.includes(key))
435 .reduce((obj, key) => {
436 obj[key] = move[key];
439 // Send move ("newmove" event) to opponent(s) (if ours)
441 if (move.color == this.game.mycolor)
443 if (this.game.moves.length >= 2) //after first move
445 const elapsed = Date.now() - this.game.initime[colorIdx];
446 // elapsed time is measured in milliseconds
447 addTime = this.game.increment - elapsed/1000;
449 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
450 if (this.game.type == "corr")
451 sendMove.message = this.corrMsg;
452 const oppsid = this.getOppSid();
455 this.st.conn.send(JSON.stringify({
461 if (this.game.type == "corr" && this.corrMsg != "")
463 // Add message to last move in BaseGame:
464 // TODO: not very good style...
465 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
469 addTime = move.addTime; //supposed transmitted
470 const nextIdx = ["w","b"].indexOf(this.vr.turn);
471 // Since corr games are stored at only one location, update should be
472 // done only by one player for each move:
473 if (this.game.type == "live" || move.color == this.game.mycolor)
475 GameStorage.update(this.gameRef.id,
480 squares: filtered_move,
481 message: this.corrMsg,
482 played: Date.now(), //TODO: on server?
483 idx: this.game.moves.length,
485 clocks: this.game.clocks.map((t,i) => i==colorIdx
486 ? this.game.clocks[i] + addTime
487 : this.game.clocks[i]),
488 initime: this.game.initime.map((t,i) => i==nextIdx
490 : this.game.initime[i]),
493 // Also update current game object:
494 this.game.moves.push(move);
495 this.game.fen = move.fen;
496 //TODO: just this.game.clocks[colorIdx] += addTime;
497 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
498 this.game.initime[nextIdx] = Date.now();
499 // Finally reset curMoveMessage if needed
500 if (this.game.type == "corr" && move.color == this.game.mycolor)
503 gameOver: function(score) {
504 this.game.mode = "analyze";
505 this.game.score = score;
506 GameStorage.update(this.gameRef.id, { score: score });