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
65 if (!!to.params["id"])
67 this.gameRef.id = to.params["id"];
68 this.gameRef.rid = to.query["rid"];
72 "game.clocks": function(newState) {
73 if (this.game.moves.length < 2)
75 // 1st move not completed yet: freeze time
76 this.virtualClocks = newState.map(s => ppt(s));
79 const currentTurn = this.vr.turn;
80 const colorIdx = ["w","b"].indexOf(currentTurn);
81 let countdown = newState[colorIdx] -
82 (Date.now() - this.game.initime[colorIdx])/1000;
83 this.virtualClocks = [0,1].map(i => {
84 const removeTime = i == colorIdx
85 ? (Date.now() - this.game.initime[colorIdx])/1000
87 return ppt(newState[i] - removeTime);
89 const myTurn = (currentTurn == this.game.mycolor);
90 let clockUpdate = setInterval(() => {
91 if (countdown <= 0 || this.vr.turn != currentTurn || this.game.score != "*")
93 clearInterval(clockUpdate);
94 if (countdown <= 0 && myTurn)
96 this.$refs["basegame"].endGame(
97 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
98 this.st.conn.send(JSON.stringify({
100 target: this.game.oppid,
106 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
107 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
111 // In case variants array was't loaded when game was retrieved
112 "st.variants": function(variantArray) {
113 if (!!this.game.vname && this.game.vname == "")
114 this.game.vname = variantArray.filter(v => v.id == this.game.vid)[0].name;
118 oppConnected: function() {
119 return this.people.indexOf(p => p.id == this.game.oppid) >= 0;
122 created: function() {
123 if (!!this.$route.params["id"])
125 this.gameRef.id = this.$route.params["id"];
126 this.gameRef.rid = this.$route.query["rid"];
129 // TODO: onopen, ask lastState informations + update observers and players status
130 const socketCloseListener = () => {
131 store.socketCloseListener(); //reinitialize connexion (in store.js)
132 this.st.conn.addEventListener('message', this.socketMessageListener);
133 this.st.conn.addEventListener('close', socketCloseListener);
135 this.st.conn.onmessage = this.socketMessageListener;
136 this.st.conn.onclose = socketCloseListener;
139 socketMessageListener: function(msg) {
140 const data = JSON.parse(msg.data);
144 // NOTE: next call will trigger processMove()
145 this.$refs["basegame"].play(data.move,
146 "receive", this.game.vname!="Dark" ? "animate" : null);
148 case "pong": //received if we sent a ping (game still alive on our side)
150 this.oppConnected = true;
151 if (this.game.type == "live") //corr games are always complete
153 // Send our "last state" informations to opponent(s)
154 const L = this.game.moves.length;
155 this.st.conn.send(JSON.stringify({
157 target: this.game.oppid,
158 gameId: this.gameRef.id,
159 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
160 score: this.game.score,
162 drawOffer: this.drawOffer,
163 clocks: this.game.clocks,
168 case "lastate": //got opponent infos about last move
170 const L = this.game.moves.length;
171 if (this.gameRef.id != data.gameId)
172 break; //games IDs don't match: nothing we can do...
173 // OK, opponent still in game (which might be over)
174 if (data.movesCount > L)
176 // Just got last move from him
177 this.$refs["basegame"].play(data.lastMove, "receive");
178 if (data.score != "*" && this.game.score == "*")
180 // Opponent resigned or aborted game, or accepted draw offer
181 // (this is not a stalemate or checkmate)
182 this.$refs["basegame"].endGame(data.score, "Opponent action");
184 this.game.clocks = data.clocks;
185 this.drawOffer = data.drawOffer;
187 else if (data.movesCount < L)
189 // We must tell last move to opponent
190 this.st.conn.send(JSON.stringify({
192 target: this.game.oppid,
193 gameId: this.gameRef.id,
194 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
195 score: this.game.score,
197 drawOffer: this.drawOffer,
198 clocks: this.game.clocks,
204 this.$refs["basegame"].endGame(
205 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
208 this.$refs["basegame"].endGame(
209 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
212 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
215 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
218 this.drawOffer = "received";
221 // TODO: just give game; observers are listed here anyway:
224 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
225 // ==> on "newmove", check "drawOffer" field
226 // TODO: also use (dis)connect info to count online players?
228 case "gamedisconnect":
229 const online = (data.code == "gameconnect");
230 // If this is an opponent ?
231 if (this.game.oppid == data.id)
232 this.oppConnected = true;
237 delete this.people[data.id];
239 this.people[data.id] = data.name;
244 offerDraw: function() {
245 // TODO: also for corr games
246 if (this.drawOffer == "received")
248 if (!confirm("Accept draw?"))
250 this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid}));
251 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
253 else if (this.drawOffer == "sent")
257 if (!confirm("Offer draw?"))
259 this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid}));
262 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
263 receiveDrawOffer: function() {
265 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
266 // if accept: send message "draw"
268 abortGame: function(event) {
269 let modalBox = document.getElementById("modalAbort");
272 // First call show options:
273 modalBox.checked = true;
277 modalBox.checked = false; //decision made: box disappear
278 const message = event.target.innerText;
279 // Next line will trigger a "gameover" event, bubbling up till here
280 this.$refs["basegame"].endGame("?", "Abort: " + message);
281 this.st.conn.send(JSON.stringify({
284 target: this.game.oppid,
288 resign: function(e) {
289 if (!confirm("Resign the game?"))
291 this.st.conn.send(JSON.stringify({
293 target: this.game.oppid,
295 // Next line will trigger a "gameover" event, bubbling up till here
296 this.$refs["basegame"].endGame(
297 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
299 // 3 cases for loading a game:
300 // - from indexedDB (running or completed live game I play)
301 // - from server (one correspondance game I play[ed] or not)
302 // - from remote peer (one live game I don't play, finished or not)
303 loadGame: function(game) {
304 const afterRetrieval = async (game) => {
305 // NOTE: variants array might not be available yet, thus the two next lines
306 const variantCell = this.st.variants.filter(v => v.id == game.vid);
307 const vname = (variantCell.length > 0 ? variantCell[0].name : "");
309 game.fen = game.fenStart; //game wasn't started
310 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
311 const tc = extractTime(game.timeControl);
314 // corr game: needs to compute the clocks + initime
315 game.clocks = [tc.mainTime, tc.mainTime];
316 game.initime = [0, 0];
317 let addTime = [0, 0];
318 for (let i=2; i<game.moves.length; i++)
320 addTime[i%2] += tc.increment -
321 (game.moves[i].played - game.moves[i-1].played);
323 for (let i=0; i<=1; i++)
324 game.clocks[i] += addTime[i];
325 const L = game.moves.length;
326 game.initime[L%2] = game.moves[L-1].played;
328 // TODO: this is not really beautiful (uid on corr players...)
329 if (gtype == "corr" && game.players[0].color == "b")
330 [ game.players[0], game.players[1] ] = [ game.players[1], game.players[0] ];
331 const myIdx = game.players.findIndex(p => {
332 return p.sid == this.st.user.sid || p.uid == this.st.user.id;
334 if (gtype == "live" && game.clocks[0] < 0) //game unstarted
336 game.clocks = [tc.mainTime, tc.mainTime];
337 game.initime[0] = Date.now();
340 // I play in this live game; corr games don't have clocks+initime
341 GameStorage.update(game.id,
344 initime: game.initime,
348 const vModule = await import("@/variants/" + vname + ".js");
349 window.V = vModule.VariantRules;
350 this.vr = new V(game.fen);
354 //TODO: people, on connect, search for opponent.......
355 console.log(myIdx + " " + game.players[1-myIdx].sid); //otherwise this is undefined:
359 this.game = Object.assign({},
361 // NOTE: assign mycolor here, since BaseGame could also be VS computer
364 increment: tc.increment,
366 mycolor: [undefined,"w","b"][myIdx+1],
367 // opponent sid not strictly required, but easier
368 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
371 if (!!this.game.oppid)
373 // Send ping to server (answer pong if players[s] are connected)
374 this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid}));
378 return afterRetrival(game);
379 if (!!this.gameRef.rid)
381 this.st.conn.send(JSON.stringify({code:"askfullgame", target:this.gameRef.rid}));
382 // TODO: just send a game request message to the remote player,
383 // and when receiving answer just call loadGame(received_game)
384 // + remote peer should have registered us as an observer
385 // (send moves updates + resign/abort/draw actions)
389 GameStorage.get(this.gameRef.id, async (game) => {
390 afterRetrieval(game);
394 // Post-process a move (which was just played)
395 processMove: function(move) {
396 if (!this.game.mycolor)
397 return; //I'm just an observer
398 // Update storage (corr or live)
399 const colorIdx = ["w","b"].indexOf(move.color);
400 // https://stackoverflow.com/a/38750895
401 const allowed_fields = ["appear", "vanish", "start", "end"];
402 const filtered_move = Object.keys(move)
403 .filter(key => allowed_fields.includes(key))
404 .reduce((obj, key) => {
405 obj[key] = move[key];
408 // Send move ("newmove" event) to opponent(s) (if ours)
410 if (move.color == this.game.mycolor)
412 if (this.game.moves.length >= 2) //after first move
414 const elapsed = Date.now() - this.game.initime[colorIdx];
415 // elapsed time is measured in milliseconds
416 addTime = this.game.increment - elapsed/1000;
418 this.st.conn.send(JSON.stringify({
420 target: this.game.oppid,
421 move: Object.assign({}, filtered_move, {addTime: addTime}),
425 addTime = move.addTime; //supposed transmitted
426 const nextIdx = ["w","b"].indexOf(this.vr.turn);
427 GameStorage.update(this.gameRef.id,
431 clocks: this.game.clocks.map((t,i) => i==colorIdx
432 ? this.game.clocks[i] + addTime
433 : this.game.clocks[i]),
434 initime: this.game.initime.map((t,i) => i==nextIdx
436 : this.game.initime[i]),
438 // Also update current game object:
439 this.game.moves.push(move);
440 this.game.fen = move.fen;
441 //TODO: just this.game.clocks[colorIdx] += addTime;
442 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
443 this.game.initime[nextIdx] = Date.now();
445 // TODO: this update function should also work for corr games
446 gameOver: function(score) {
447 this.game.mode = "analyze";
448 this.game.score = score;
449 GameStorage.update(this.gameRef.id, { score: score });