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 // TODO: also show players names
15 div 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 div(v-if="game.mode=='corr'")
21 textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg")
22 div(v-show="cursor>=0") {{ moves[cursor].message }}
26 // TODO: movelist dans basegame et chat ici
27 // ==> après, implémenter/vérifier les passages de challenges + parties en cours
29 // + problèmes, habiller et publier. (+ corr...)
30 // when send to chat (or a move), reach only this group (send gid along)
34 import BaseGame from "@/components/BaseGame.vue";
35 //import Chat from "@/components/Chat.vue";
36 //import MoveList from "@/components/MoveList.vue";
37 import { store } from "@/store";
38 import { GameStorage } from "@/utils/gameStorage";
39 import { ppt } from "@/utils/datetime";
40 import { extractTime } from "@/utils/timeControl";
47 // gameRef: to find the game in (potentially remote) storage
51 gameRef: { //given in URL (rid = remote ID)
55 game: {}, //passed to BaseGame
56 corrMsg: "", //to send offline messages in corr games
57 virtualClocks: [0, 0], //initialized with true game.clocks
58 vr: null, //"variant rules" object initialized from FEN
59 drawOffer: "", //TODO: use for button style
60 people: [], //players + observers
64 "$route": function(to, from) {
65 this.gameRef.id = to.params["id"];
66 this.gameRef.rid = to.query["rid"];
69 "game.clocks": function(newState) {
70 if (this.game.moves.length < 2)
72 // 1st move not completed yet: freeze time
73 this.virtualClocks = newState.map(s => ppt(s));
76 const currentTurn = this.vr.turn;
77 const colorIdx = ["w","b"].indexOf(currentTurn);
78 let countdown = newState[colorIdx] -
79 (Date.now() - this.game.initime[colorIdx])/1000;
80 this.virtualClocks = [0,1].map(i => {
81 const removeTime = i == colorIdx
82 ? (Date.now() - this.game.initime[colorIdx])/1000
84 return ppt(newState[i] - removeTime);
86 const myTurn = (currentTurn == this.game.mycolor);
87 let clockUpdate = setInterval(() => {
88 if (countdown <= 0 || this.vr.turn != currentTurn || this.game.score != "*")
90 clearInterval(clockUpdate);
91 if (countdown <= 0 && myTurn)
93 this.$refs["basegame"].endGame(
94 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
95 const oppsid = this.getOppSid();
98 this.st.conn.send(JSON.stringify({
107 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
108 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
112 // In case variants array was't loaded when game was retrieved
113 "st.variants": function(variantArray) {
114 if (!!this.game.vname && this.game.vname == "")
116 this.game.vname = variantArray.filter(v =>
117 v.id == this.game.vid)[0].name;
121 // TODO: redundant code with Hall.vue (related to people array)
122 created: function() {
123 // Always add myself to players' list
124 const my = this.st.user;
125 this.people.push({sid:my.sid, id:my.id, name:my.name});
126 if (!!this.$route.params["id"])
128 this.gameRef.id = this.$route.params["id"];
129 this.gameRef.rid = this.$route.query["rid"];
132 // 0.1] Ask server for room composition:
133 const funcPollClients = () => {
134 this.st.conn.send(JSON.stringify({code:"pollclients"}));
136 if (!!this.st.conn && this.st.conn.readyState == 1) //1 == OPEN state
138 else //socket not ready yet (initial loading)
139 this.st.conn.onopen = funcPollClients;
140 this.st.conn.onmessage = this.socketMessageListener;
141 const socketCloseListener = () => {
142 store.socketCloseListener(); //reinitialize connexion (in store.js)
143 this.st.conn.addEventListener('message', this.socketMessageListener);
144 this.st.conn.addEventListener('close', socketCloseListener);
146 this.st.conn.onclose = socketCloseListener;
149 getOppSid: function() {
150 if (!!this.game.oppsid)
151 return this.game.oppsid;
152 const opponent = this.people.find(p => p.id == this.game.oppid);
153 return (!!opponent ? opponent.sid : null);
155 socketMessageListener: function(msg) {
156 const data = JSON.parse(msg.data);
159 // 0.2] Receive clients list (just socket IDs)
162 data.sockIds.forEach(sid => {
163 this.people.push({sid:sid, id:0, name:""});
165 this.st.conn.send(JSON.stringify({code:"askidentity", target:sid}));
171 // Request for identification: reply if I'm not anonymous
172 if (this.st.user.id > 0)
174 this.st.conn.send(JSON.stringify(
175 // people[0] instead of st.user to avoid sending email
176 {code:"identity", user:this.people[0], target:data.from}));
182 const pIdx = this.people.findIndex(p => p.sid == data.user.sid);
183 this.people[pIdx].id = data.user.id;
184 this.people[pIdx].name = data.user.name;
188 // NOTE: next call will trigger processMove()
189 this.$refs["basegame"].play(data.move,
190 "receive", this.game.vname!="Dark" ? "animate" : null);
192 case "pong": //received if we sent a ping (game still alive on our side)
194 if (this.game.type == "live") //corr games are always complete
196 // Send our "last state" informations to opponent(s)
197 const L = this.game.moves.length;
198 this.st.conn.send(JSON.stringify({
200 target: this.getOppSid(), //he's connected for sure
201 gameId: this.gameRef.id,
202 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
203 score: this.game.score,
205 drawOffer: this.drawOffer,
206 clocks: this.game.clocks,
211 case "lastate": //got opponent infos about last move
213 const L = this.game.moves.length;
214 if (this.gameRef.id != data.gameId)
215 break; //games IDs don't match: nothing we can do...
216 // OK, opponent still in game (which might be over)
217 if (data.movesCount > L)
219 // Just got last move from him
220 this.$refs["basegame"].play(data.lastMove, "receive");
221 if (data.score != "*" && this.game.score == "*")
223 // Opponent resigned or aborted game, or accepted draw offer
224 // (this is not a stalemate or checkmate)
225 this.$refs["basegame"].endGame(data.score, "Opponent action");
227 this.game.clocks = data.clocks;
228 this.drawOffer = data.drawOffer;
230 else if (data.movesCount < L)
232 // We must tell last move to opponent
233 this.st.conn.send(JSON.stringify({
235 target: this.getOppSid(), //we know he is connected
236 gameId: this.gameRef.id,
237 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
238 score: this.game.score,
240 drawOffer: this.drawOffer,
241 clocks: this.game.clocks,
247 this.$refs["basegame"].endGame(
248 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
251 this.$refs["basegame"].endGame(
252 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
255 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
258 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
261 this.drawOffer = "received";
264 // TODO: just give game; observers are listed here anyway:
265 // ==> mark request SID as someone to send moves to
266 // NOT to all people array: our opponent can send moves too!
269 // and when receiving answer just call loadGame(received_game)
270 this.loadGame(data.game);
272 // TODO: drawaccepted (click draw button before sending move
273 // ==> draw offer in move)
274 // ==> on "newmove", check "drawOffer" field
277 // TODO: if opponent connect, trigger lastate chain of events...
278 this.people.push({name:"", id:0, sid:data.sid});
279 this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid}));
283 ArrayFun.remove(this.people, p => p.sid == data.sid);
287 offerDraw: function() {
288 // TODO: also for corr games
289 if (this.drawOffer == "received")
291 if (!confirm("Accept draw?"))
293 const oppsid = this.getOppSid();
295 this.st.conn.send(JSON.stringify({code:"draw", target:oppsid}));
296 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
298 else if (this.drawOffer == "sent")
302 if (!confirm("Offer draw?"))
304 const oppsid = this.getOppSid();
306 this.st.conn.send(JSON.stringify({code:"drawoffer", target:oppsid}));
309 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
310 receiveDrawOffer: function() {
312 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
313 // if accept: send message "draw"
315 abortGame: function(event) {
316 let modalBox = document.getElementById("modalAbort");
319 // First call show options:
320 modalBox.checked = true;
324 modalBox.checked = false; //decision made: box disappear
325 const message = event.target.innerText;
326 // Next line will trigger a "gameover" event, bubbling up till here
327 this.$refs["basegame"].endGame("?", "Abort: " + message);
328 const oppsid = this.getOppSid();
331 this.st.conn.send(JSON.stringify({
339 resign: function(e) {
340 if (!confirm("Resign the game?"))
342 const oppsid = this.getOppSid();
345 this.st.conn.send(JSON.stringify({
350 // Next line will trigger a "gameover" event, bubbling up till here
351 this.$refs["basegame"].endGame(
352 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
354 // 3 cases for loading a game:
355 // - from indexedDB (running or completed live game I play)
356 // - from server (one correspondance game I play[ed] or not)
357 // - from remote peer (one live game I don't play, finished or not)
358 loadGame: function(game) {
359 const afterRetrieval = async (game) => {
360 // NOTE: variants array might not be available yet, thus the two next lines
361 const variantCell = this.st.variants.filter(v => v.id == game.vid);
362 const vname = (variantCell.length > 0 ? variantCell[0].name : "");
364 game.fen = game.fenStart; //game wasn't started
365 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
366 // TODO: this is not really beautiful (uid on corr players...)
367 if (gtype == "corr" && game.players[0].color == "b")
368 [ game.players[0], game.players[1] ] = [ game.players[1], game.players[0] ];
369 const myIdx = game.players.findIndex(p => {
370 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
372 const tc = extractTime(game.timeControl);
375 // corr game: needs to compute the clocks + initime
376 game.clocks = [tc.mainTime, tc.mainTime];
377 game.initime = [0, 0];
378 const L = game.moves.length;
381 let addTime = [0, 0];
382 for (let i=2; i<L; i++)
384 addTime[i%2] += tc.increment -
385 (game.moves[i].played - game.moves[i-1].played);
387 for (let i=0; i<=1; i++)
388 game.clocks[i] += addTime[i];
391 game.initime[L%2] = game.moves[L-1].played;
393 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
395 game.clocks = [tc.mainTime, tc.mainTime];
396 game.initime[0] = Date.now();
399 // I play in this live game; corr games don't have clocks+initime
400 GameStorage.update(game.id,
403 initime: game.initime,
407 const vModule = await import("@/variants/" + vname + ".js");
408 window.V = vModule.VariantRules;
409 this.vr = new V(game.fen);
410 this.game = Object.assign({},
412 // NOTE: assign mycolor here, since BaseGame could also be VS computer
415 increment: tc.increment,
417 mycolor: [undefined,"w","b"][myIdx+1],
418 // opponent sid not strictly required (or available), but easier
419 // at least oppsid or oppid is available anyway:
420 oppsid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
421 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].uid),
424 if (!!this.game.oppid)
426 // Send ping to server (answer pong if players[s] are connected)
427 this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid}));
431 return afterRetrival(game);
432 if (!!this.gameRef.rid)
434 this.st.conn.send(JSON.stringify(
435 {code:"askfullgame", target:this.gameRef.rid}));
436 // (send moves updates + resign/abort/draw actions)
440 GameStorage.get(this.gameRef.id, async (game) => {
441 afterRetrieval(game);
445 // Post-process a move (which was just played)
446 processMove: function(move) {
447 if (!this.game.mycolor)
448 return; //I'm just an observer
449 // Update storage (corr or live)
450 const colorIdx = ["w","b"].indexOf(move.color);
451 // https://stackoverflow.com/a/38750895
452 const allowed_fields = ["appear", "vanish", "start", "end"];
453 const filtered_move = Object.keys(move)
454 .filter(key => allowed_fields.includes(key))
455 .reduce((obj, key) => {
456 obj[key] = move[key];
459 // Send move ("newmove" event) to opponent(s) (if ours)
461 if (move.color == this.game.mycolor)
463 if (this.game.moves.length >= 2) //after first move
465 const elapsed = Date.now() - this.game.initime[colorIdx];
466 // elapsed time is measured in milliseconds
467 addTime = this.game.increment - elapsed/1000;
469 this.st.conn.send(JSON.stringify({
471 target: this.game.oppid,
472 move: Object.assign({}, filtered_move, {addTime: addTime}),
476 addTime = move.addTime; //supposed transmitted
477 const nextIdx = ["w","b"].indexOf(this.vr.turn);
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]),
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();
496 // TODO: this update function should also work for corr games
497 gameOver: function(score) {
498 this.game.mode = "analyze";
499 this.game.score = score;
500 GameStorage.update(this.gameRef.id, { score: score });