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 // TODO: how to know who is observing ? Send message to everyone with game ID ?
31 // and then just listen to (dis)connect events
32 // server always send "connect on " + URL ; then add to observers if game...
33 // router when access a game page tell to server I joined + game ID (no need rid)
34 // and ask server for current joined (= observers)
35 // when send to chat (or a move), reach only this group (send gid along)
36 // -> doivent être enregistrés comme observers au niveau du serveur...
37 // non: poll users + events startObserving / stopObserving
38 // (à faire au niveau du routeur ?)
42 import BaseGame from "@/components/BaseGame.vue";
43 //import Chat from "@/components/Chat.vue";
44 //import MoveList from "@/components/MoveList.vue";
45 import { store } from "@/store";
46 import { GameStorage } from "@/utils/gameStorage";
47 import { ppt } from "@/utils/datetime";
54 // gameRef: to find the game in (potentially remote) storage
58 gameRef: { //given in URL (rid = remote ID)
62 game: { }, //passed to BaseGame
64 corrMsg: "", //to send offline messages in corr games
65 virtualClocks: [0, 0], //initialized with true game.clocks
66 vr: null, //"variant rules" object initialized from FEN
67 drawOffer: "", //TODO: use for button style
68 people: [ ], //potential observers (TODO)
73 if (!!to.params["id"])
75 this.gameRef.id = to.params["id"];
76 this.gameRef.rid = to.query["rid"];
80 "game.clocks": function(newState) {
81 this.virtualClocks = newState.map(s => ppt(s));
82 const currentTurn = this.vr.turn;
83 const colorIdx = ["w","b"].indexOf(currentTurn);
84 let countdown = newState[colorIdx] -
85 (Date.now() - this.game.initime[colorIdx])/1000;
86 const myTurn = (currentTurn == this.game.mycolor);
87 let clockUpdate = setInterval(() => {
88 if (countdown <= 0 || this.vr.turn != currentTurn)
90 clearInterval(clockUpdate);
91 if (countdown <= 0 && myTurn)
93 this.$refs["basegame"].endGame(
94 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
95 this.st.conn.send(JSON.stringify({
97 target: this.game.oppid,
103 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
104 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
109 created: function() {
110 if (!!this.$route.params["id"])
112 this.gameRef.id = this.$route.params["id"];
113 this.gameRef.rid = this.$route.query["rid"];
116 // TODO: onopen, ask lastState informations + update observers and players status
117 const socketCloseListener = () => {
118 store.socketCloseListener(); //reinitialize connexion (in store.js)
119 this.st.conn.addEventListener('message', socketMessageListener);
120 this.st.conn.addEventListener('close', socketCloseListener);
122 this.st.conn.onmessage = this.socketMessageListener;
123 this.st.conn.onclose = socketCloseListener;
126 socketMessageListener: function(msg) {
127 const data = JSON.parse(msg.data);
131 // NOTE: next call will trigger processMove()
132 this.$refs["basegame"].play(data.move,
133 "receive", this.game.vname!="Dark" ? "animate" : null);
135 case "pong": //received if we sent a ping (game still alive on our side)
137 this.oppConnected = true;
138 // Send our "last state" informations to opponent(s)
139 const L = this.game.moves.length;
140 this.st.conn.send(JSON.stringify({
142 target: this.game.oppid,
143 gameId: this.gameRef.id,
144 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
145 score: this.game.score,
147 drawOffer: this.drawOffer,
148 clocks: this.game.clocks,
152 case "lastate": //got opponent infos about last move
154 const L = this.game.moves.length;
155 if (this.gameRef.id != data.gameId)
156 break; //games IDs don't match: nothing we can do...
157 // OK, opponent still in game (which might be over)
158 if (data.movesCount > L)
160 // Just got last move from him
161 this.$refs["basegame"].play(data.lastMove, "receive");
162 if (data.score != "*" && this.game.score == "*")
164 // Opponent resigned or aborted game, or accepted draw offer
165 // (this is not a stalemate or checkmate)
166 this.$refs["basegame"].endGame(data.score, "Opponent action");
168 this.game.clocks = data.clocks;
169 this.drawOffer = data.drawOffer;
171 else if (data.movesCount < L)
173 // We must tell last move to opponent
174 this.st.conn.send(JSON.stringify({
176 target: this.game.oppid,
177 gameId: this.gameRef.id,
178 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
179 score: this.game.score,
181 drawOffer: this.drawOffer,
182 clocks: this.game.clocks,
188 this.$refs["basegame"].endGame(
189 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
192 this.$refs["basegame"].endGame(
193 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
196 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
199 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
202 this.drawOffer = "received";
205 // TODO: just give game; observers are listed here anyway:
208 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
209 // ==> on "newmove", check "drawOffer" field
210 // TODO: also use (dis)connect info to count online players?
212 case "gamedisconnect":
213 const online = (data.code == "gameconnect");
214 // If this is an opponent ?
215 if (this.game.oppid == data.id)
216 this.oppConnected = true;
221 delete this.people[data.id];
223 this.people[data.id] = data.name;
228 offerDraw: function() {
229 // TODO: also for corr games
230 if (this.drawOffer == "received")
232 if (!confirm("Accept draw?"))
234 this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid}));
235 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
237 else if (this.drawOffer == "sent")
241 if (!confirm("Offer draw?"))
243 this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid}));
246 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
247 receiveDrawOffer: function() {
249 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
250 // if accept: send message "draw"
252 abortGame: function(event) {
253 let modalBox = document.getElementById("modalAbort");
256 // First call show options:
257 modalBox.checked = true;
261 modalBox.checked = false; //decision made: box disappear
262 const message = event.target.innerText;
263 // Next line will trigger a "gameover" event, bubbling up till here
264 this.$refs["basegame"].endGame("?", "Abort: " + message);
265 this.st.conn.send(JSON.stringify({
268 target: this.game.oppid,
272 resign: function(e) {
273 if (!confirm("Resign the game?"))
275 this.st.conn.send(JSON.stringify({
277 target: this.game.oppid,
279 // Next line will trigger a "gameover" event, bubbling up till here
280 this.$refs["basegame"].endGame(
281 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
283 // 3 cases for loading a game:
284 // - from indexedDB (running or completed live game I play)
285 // - from server (one correspondance game I play[ed] or not)
286 // - from remote peer (one live game I don't play, finished or not)
287 loadGame: function(game) {
288 const afterRetrieval = async (game) => {
289 const vModule = await import("@/variants/" + game.vname + ".js");
290 window.V = vModule.VariantRules;
291 this.vr = new V(game.fen);
292 const myIdx = game.players.findIndex(p => p.sid == this.st.user.sid);
293 this.game = Object.assign({},
295 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
297 mycolor: [undefined,"w","b"][myIdx+1],
298 // opponent sid not strictly required, but easier
299 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
302 if (!!this.game.oppid)
304 // Send ping to server (answer pong if players[s] are connected)
305 this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid}));
309 return afterRetrival(game);
310 if (!!this.gameRef.rid)
312 this.st.conn.send(JSON.stringify({code:"askfullgame", target:this.gameRef.rid}));
313 // TODO: just send a game request message to the remote player,
314 // and when receiving answer just call loadGame(received_game)
315 // + remote peer should have registered us as an observer
316 // (send moves updates + resign/abort/draw actions)
320 GameStorage.get(this.gameRef.id, async (game) => {
321 afterRetrieval(game);
325 // Post-process a move (which was just played)
326 processMove: function(move) {
327 if (!this.game.mycolor)
328 return; //I'm just an observer
329 // Update storage (corr or live)
330 const colorIdx = ["w","b"].indexOf(move.color);
331 // https://stackoverflow.com/a/38750895
332 const allowed_fields = ["appear", "vanish", "start", "end"];
333 const filtered_move = Object.keys(move)
334 .filter(key => allowed_fields.includes(key))
335 .reduce((obj, key) => {
336 obj[key] = move[key];
339 // Send move ("newmove" event) to opponent(s) (if ours)
340 let addTime = undefined;
341 if (move.color == this.game.mycolor)
343 const elapsed = Date.now() - this.game.initime[colorIdx];
344 // elapsed time is measured in milliseconds
345 addTime = this.game.increment - elapsed/1000;
346 this.st.conn.send(JSON.stringify({
348 target: this.game.oppid,
349 move: Object.assign({}, filtered_move, {addTime: addTime}),
353 addTime = move.addTime; //supposed transmitted
354 const nextIdx = ["w","b"].indexOf(this.vr.turn);
355 GameStorage.update(this.gameRef.id,
363 // Also update current game object:
364 this.game.moves.push(move);
365 this.game.fen = move.fen;
366 //TODO: just this.game.clocks[colorIdx] += (!!addTime ? addTime : 0);
367 this.$set(this.game.clocks, colorIdx,
368 this.game.clocks[colorIdx] + (!!addTime ? addTime : 0));
369 this.game.initime[nextIdx] = Date.now();
371 // TODO: this update function should also work for corr games
372 gameOver: function(score) {
373 this.game.mode = "analyze";
374 GameStorage.update(this.gameRef.id,