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.type=='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 let clockUpdate = setInterval(() => {
89 if (countdown < 0 || this.vr.turn != currentTurn || this.game.score != "*")
91 clearInterval(clockUpdate);
94 this.$refs["basegame"].endGame(
95 this.vr.turn=="w" ? "0-1" : "1-0", "Time");
100 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
101 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
106 // TODO: redundant code with Hall.vue (related to people array)
107 created: function() {
108 // Always add myself to players' list
109 const my = this.st.user;
110 this.people.push({sid:my.sid, id:my.id, name:my.name});
111 if (!!this.$route.params["id"])
113 this.gameRef.id = this.$route.params["id"];
114 this.gameRef.rid = this.$route.query["rid"];
117 // 0.1] Ask server for room composition:
118 const funcPollClients = () => {
119 this.st.conn.send(JSON.stringify({code:"pollclients"}));
121 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
123 else //socket not ready yet (initial loading)
124 this.st.conn.onopen = funcPollClients;
125 this.st.conn.onmessage = this.socketMessageListener;
126 const socketCloseListener = () => {
127 store.socketCloseListener(); //reinitialize connexion (in store.js)
128 this.st.conn.addEventListener('message', this.socketMessageListener);
129 this.st.conn.addEventListener('close', socketCloseListener);
131 this.st.conn.onclose = socketCloseListener;
134 getOppSid: function() {
135 if (!!this.game.oppsid)
136 return this.game.oppsid;
137 const opponent = this.people.find(p => p.id == this.game.oppid);
138 return (!!opponent ? opponent.sid : null);
140 socketMessageListener: function(msg) {
141 const data = JSON.parse(msg.data);
144 // 0.2] Receive clients list (just socket IDs)
147 data.sockIds.forEach(sid => {
148 this.people.push({sid:sid, id:0, name:""});
150 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
156 // Request for identification: reply if I'm not anonymous
157 if (this.st.user.id > 0)
159 this.st.conn.send(JSON.stringify(
160 // people[0] instead of st.user to avoid sending email
161 {code:"identity", user:this.people[0], target:data.from}));
167 let player = this.people.find(p => p.sid == data.user.sid);
168 player.id = data.user.id;
169 player.name = data.user.name;
170 // Sending last state only for live games: corr games are complete
171 if (this.game.type == "live" && this.game.oppsid == player.sid)
173 // Send our "last state" informations to opponent
174 const L = this.game.moves.length;
175 this.st.conn.send(JSON.stringify({
180 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
181 score: this.game.score,
183 drawOffer: this.drawOffer,
184 clocks: this.game.clocks,
191 // NOTE: this call to play() will trigger processMove()
192 this.$refs["basegame"].play(data.move,
193 "receive", this.game.vname!="Dark" ? "animate" : null);
195 case "lastate": //got opponent infos about last move
197 const L = this.game.moves.length;
198 if (data.movesCount > L)
200 // Just got last move from him
201 this.$refs["basegame"].play(data.lastMove,
202 "receive", this.game.vname!="Dark" ? "animate" : null);
203 if (data.score != "*" && this.game.score == "*")
205 // Opponent resigned or aborted game, or accepted draw offer
206 // (this is not a stalemate or checkmate)
207 this.$refs["basegame"].endGame(data.score, "Opponent action");
209 this.game.clocks = data.clocks; //TODO: check this?
210 this.drawOffer = data.drawOffer; //does opponent offer draw?
215 this.$refs["basegame"].endGame(
216 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
219 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
222 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
225 this.drawOffer = "received";
228 // TODO: just give game; observers are listed here anyway:
229 // ==> mark request SID as someone to send moves to
230 // NOT to all people array: our opponent can send moves too!
233 // and when receiving answer just call loadGame(received_game)
234 this.loadGame(data.game);
236 // TODO: drawaccepted (click draw button before sending move
237 // ==> draw offer in move)
238 // ==> on "newmove", check "drawOffer" field
241 this.people.push({name:"", id:0, sid:data.sid});
242 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
246 ArrayFun.remove(this.people, p => p.sid == data.sid);
250 offerDraw: function() {
251 // TODO: also for corr games
252 if (this.drawOffer == "received")
254 if (!confirm("Accept draw?"))
256 const oppsid = this.getOppSid();
258 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
259 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
261 else if (this.drawOffer == "sent")
265 if (!confirm("Offer draw?"))
267 const oppsid = this.getOppSid();
269 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
272 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
273 receiveDrawOffer: function() {
275 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
276 // if accept: send message "draw"
278 abortGame: function(event) {
279 let modalBox = document.getElementById("modalAbort");
282 // First call show options:
283 modalBox.checked = true;
287 modalBox.checked = false; //decision made: box disappear
288 const message = event.target.innerText;
289 // Next line will trigger a "gameover" event, bubbling up till here
290 this.$refs["basegame"].endGame("?", "Abort: " + message);
291 const oppsid = this.getOppSid();
294 this.st.conn.send(JSON.stringify({
302 resign: function(e) {
303 if (!confirm("Resign the game?"))
305 const oppsid = this.getOppSid();
308 this.st.conn.send(JSON.stringify({
313 // Next line will trigger a "gameover" event, bubbling up till here
314 this.$refs["basegame"].endGame(
315 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
317 // 3 cases for loading a game:
318 // - from indexedDB (running or completed live game I play)
319 // - from server (one correspondance game I play[ed] or not)
320 // - from remote peer (one live game I don't play, finished or not)
321 loadGame: function(game) {
322 const afterRetrieval = async (game) => {
323 const vModule = await import("@/variants/" + game.vname + ".js");
324 window.V = vModule.VariantRules;
325 this.vr = new V(game.fen);
326 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
327 const tc = extractTime(game.timeControl);
330 if (game.players[0].color == "b")
332 // Adopt the same convention for live and corr games: [0] = white
333 [ game.players[0], game.players[1] ] =
334 [ game.players[1], game.players[0] ];
336 // corr game: needs to compute the clocks + initime
337 game.clocks = [tc.mainTime, tc.mainTime];
338 game.initime = [0, 0];
339 const L = game.moves.length;
340 game.moves.sort((m1,m2) => m1.idx - m2.idx); //in case of
343 let addTime = [0, 0];
344 for (let i=2; i<L; i++)
346 addTime[i%2] += tc.increment -
347 (game.moves[i].played - game.moves[i-1].played);
349 for (let i=0; i<=1; i++)
350 game.clocks[i] += addTime[i];
353 game.initime[L%2] = game.moves[L-1].played;
354 // Now that we used idx and played, re-format moves as for live games
355 game.moves = game.moves.map( (m) => {
366 const myIdx = game.players.findIndex(p => {
367 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
369 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
371 game.clocks = [tc.mainTime, tc.mainTime];
372 game.initime[0] = Date.now();
375 // I play in this live game; corr games don't have clocks+initime
376 GameStorage.update(game.id,
379 initime: game.initime,
383 this.game = Object.assign({},
385 // NOTE: assign mycolor here, since BaseGame could also be VS computer
388 increment: tc.increment,
389 mycolor: [undefined,"w","b"][myIdx+1],
390 // opponent sid not strictly required (or available), but easier
391 // at least oppsid or oppid is available anyway:
392 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
393 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
398 return afterRetrival(game);
399 if (!!this.gameRef.rid)
402 this.st.conn.send(JSON.stringify(
403 {code:"askfullgame", target:this.gameRef.rid}));
404 // (send moves updates + resign/abort/draw actions)
408 // Local or corr game
409 GameStorage.get(this.gameRef.id, afterRetrieval);
412 // Post-process a move (which was just played)
413 processMove: function(move) {
414 if (!this.game.mycolor)
415 return; //I'm just an observer
416 // Update storage (corr or live)
417 const colorIdx = ["w","b"].indexOf(move.color);
418 // https://stackoverflow.com/a/38750895
419 const allowed_fields = ["appear", "vanish", "start", "end"];
420 const filtered_move = Object.keys(move)
421 .filter(key => allowed_fields.includes(key))
422 .reduce((obj, key) => {
423 obj[key] = move[key];
426 // Send move ("newmove" event) to opponent(s) (if ours)
428 if (move.color == this.game.mycolor)
430 if (this.game.moves.length >= 2) //after first move
432 const elapsed = Date.now() - this.game.initime[colorIdx];
433 // elapsed time is measured in milliseconds
434 addTime = this.game.increment - elapsed/1000;
436 let sendMove = Object.assign({}, filtered_move, {addTime: addTime});
437 if (this.game.type == "corr")
438 sendMove.message = this.corrMsg;
439 const oppsid = this.getOppSid();
442 this.st.conn.send(JSON.stringify({
448 if (this.game.type == "corr" && this.corrMsg != "")
450 // Add message to last move in BaseGame:
451 // TODO: not very good style...
452 this.$refs["basegame"].setCurrentMessage(this.corrMsg);
456 addTime = move.addTime; //supposed transmitted
457 const nextIdx = ["w","b"].indexOf(this.vr.turn);
458 // Since corr games are stored at only one location, update should be
459 // done only by one player for each move:
460 if (this.game.type == "live" || move.color == this.game.mycolor)
462 if (this.game.type == "corr")
464 GameStorage.update(this.gameRef.id,
469 squares: filtered_move,
470 message: this.corrMsg,
471 played: Date.now(), //TODO: on server?
472 idx: this.game.moves.length,
478 GameStorage.update(this.gameRef.id,
482 clocks: this.game.clocks.map((t,i) => i==colorIdx
483 ? this.game.clocks[i] + addTime
484 : this.game.clocks[i]),
485 initime: this.game.initime.map((t,i) => i==nextIdx
487 : this.game.initime[i]),
491 // Also update current game object:
492 this.game.moves.push(move);
493 this.game.fen = move.fen;
494 //TODO: just this.game.clocks[colorIdx] += addTime;
495 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
496 this.game.initime[nextIdx] = Date.now();
497 // Finally reset curMoveMessage if needed
498 if (this.game.type == "corr" && move.color == this.game.mycolor)
501 gameOver: function(score) {
502 this.game.mode = "analyze";
503 this.game.score = score;
504 GameStorage.update(this.gameRef.id, { score: score });