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";
48 import { extractTime } from "@/utils/timeControl";
55 // gameRef: to find the game in (potentially remote) storage
59 gameRef: { //given in URL (rid = remote ID)
63 game: { }, //passed to BaseGame
65 corrMsg: "", //to send offline messages in corr games
66 virtualClocks: [0, 0], //initialized with true game.clocks
67 vr: null, //"variant rules" object initialized from FEN
68 drawOffer: "", //TODO: use for button style
69 people: [ ], //potential observers (TODO)
74 if (!!to.params["id"])
76 this.gameRef.id = to.params["id"];
77 this.gameRef.rid = to.query["rid"];
81 "game.clocks": function(newState) {
82 if (this.game.moves.length < 2)
84 // 1st move not completed yet: freeze time
85 this.virtualClocks = newState.map(s => ppt(s));
88 const currentTurn = this.vr.turn;
89 const colorIdx = ["w","b"].indexOf(currentTurn);
90 let countdown = newState[colorIdx] -
91 (Date.now() - this.game.initime[colorIdx])/1000;
92 this.virtualClocks = [0,1].map(i => {
93 const removeTime = i == colorIdx
94 ? (Date.now() - this.game.initime[colorIdx])/1000
96 return ppt(newState[i] - removeTime);
98 const myTurn = (currentTurn == this.game.mycolor);
99 let clockUpdate = setInterval(() => {
100 if (countdown <= 0 || this.vr.turn != currentTurn)
102 clearInterval(clockUpdate);
103 if (countdown <= 0 && myTurn)
105 this.$refs["basegame"].endGame(
106 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
107 this.st.conn.send(JSON.stringify({
109 target: this.game.oppid,
115 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
116 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
120 // In case variants array was't loaded when game was retrieved
121 "st.variants": function(variantArray) {
122 if (!!this.game.vname && this.game.vname == "")
123 this.game.vname = variantArray.filter(v => v.id == this.game.vid)[0].name;
126 created: function() {
127 if (!!this.$route.params["id"])
129 this.gameRef.id = this.$route.params["id"];
130 this.gameRef.rid = this.$route.query["rid"];
133 // TODO: onopen, ask lastState informations + update observers and players status
134 const socketCloseListener = () => {
135 store.socketCloseListener(); //reinitialize connexion (in store.js)
136 this.st.conn.addEventListener('message', this.socketMessageListener);
137 this.st.conn.addEventListener('close', socketCloseListener);
139 this.st.conn.onmessage = this.socketMessageListener;
140 this.st.conn.onclose = socketCloseListener;
143 socketMessageListener: function(msg) {
144 const data = JSON.parse(msg.data);
148 // NOTE: next call will trigger processMove()
149 this.$refs["basegame"].play(data.move,
150 "receive", this.game.vname!="Dark" ? "animate" : null);
152 case "pong": //received if we sent a ping (game still alive on our side)
154 this.oppConnected = true;
155 // Send our "last state" informations to opponent(s)
156 const L = this.game.moves.length;
157 this.st.conn.send(JSON.stringify({
159 target: this.game.oppid,
160 gameId: this.gameRef.id,
161 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
162 score: this.game.score,
164 drawOffer: this.drawOffer,
165 clocks: this.game.clocks,
169 case "lastate": //got opponent infos about last move
171 const L = this.game.moves.length;
172 if (this.gameRef.id != data.gameId)
173 break; //games IDs don't match: nothing we can do...
174 // OK, opponent still in game (which might be over)
175 if (data.movesCount > L)
177 // Just got last move from him
178 this.$refs["basegame"].play(data.lastMove, "receive");
179 if (data.score != "*" && this.game.score == "*")
181 // Opponent resigned or aborted game, or accepted draw offer
182 // (this is not a stalemate or checkmate)
183 this.$refs["basegame"].endGame(data.score, "Opponent action");
185 this.game.clocks = data.clocks;
186 this.drawOffer = data.drawOffer;
188 else if (data.movesCount < L)
190 // We must tell last move to opponent
191 this.st.conn.send(JSON.stringify({
193 target: this.game.oppid,
194 gameId: this.gameRef.id,
195 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
196 score: this.game.score,
198 drawOffer: this.drawOffer,
199 clocks: this.game.clocks,
205 this.$refs["basegame"].endGame(
206 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
209 this.$refs["basegame"].endGame(
210 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
213 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
216 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
219 this.drawOffer = "received";
222 // TODO: just give game; observers are listed here anyway:
225 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
226 // ==> on "newmove", check "drawOffer" field
227 // TODO: also use (dis)connect info to count online players?
229 case "gamedisconnect":
230 const online = (data.code == "gameconnect");
231 // If this is an opponent ?
232 if (this.game.oppid == data.id)
233 this.oppConnected = true;
238 delete this.people[data.id];
240 this.people[data.id] = data.name;
245 offerDraw: function() {
246 // TODO: also for corr games
247 if (this.drawOffer == "received")
249 if (!confirm("Accept draw?"))
251 this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid}));
252 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
254 else if (this.drawOffer == "sent")
258 if (!confirm("Offer draw?"))
260 this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid}));
263 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
264 receiveDrawOffer: function() {
266 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
267 // if accept: send message "draw"
269 abortGame: function(event) {
270 let modalBox = document.getElementById("modalAbort");
273 // First call show options:
274 modalBox.checked = true;
278 modalBox.checked = false; //decision made: box disappear
279 const message = event.target.innerText;
280 // Next line will trigger a "gameover" event, bubbling up till here
281 this.$refs["basegame"].endGame("?", "Abort: " + message);
282 this.st.conn.send(JSON.stringify({
285 target: this.game.oppid,
289 resign: function(e) {
290 if (!confirm("Resign the game?"))
292 this.st.conn.send(JSON.stringify({
294 target: this.game.oppid,
296 // Next line will trigger a "gameover" event, bubbling up till here
297 this.$refs["basegame"].endGame(
298 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
300 // 3 cases for loading a game:
301 // - from indexedDB (running or completed live game I play)
302 // - from server (one correspondance game I play[ed] or not)
303 // - from remote peer (one live game I don't play, finished or not)
304 loadGame: function(game) {
305 const afterRetrieval = async (game) => {
306 // NOTE: variants array might not be available yet, thus the two next lines
307 const variantCell = this.st.variants.filter(v => v.id == game.vid);
308 const vname = (variantCell.length > 0 ? variantCell[0].name : "");
310 game.fen = game.fenStart; //game wasn't started
311 const gtype = (game.timeControl.indexOf('d') >= 0 ? "corr" : "live");
314 // corr game: needs to compute the clocks + initime
315 //if (game.players[i].rtime < 0) initime = Date.now(), else compute,
316 //also using move.played fields
317 game.clocks = [-1, -1];
318 game.initime = [0, 0];
319 // TODO: compute clocks + initime
321 const tc = extractTime(game.timeControl);
322 const myIdx = game.players.findIndex(p => p.sid == this.st.user.sid);
323 if (game.clocks[0] < 0) //game unstarted
325 game.clocks = [tc.mainTime, tc.mainTime];
326 game.initime[0] = Date.now();
327 if (myIdx >= 0) //I play in this game
329 GameStorage.update(game.gameId,
332 initime: game.initime,
336 const vModule = await import("@/variants/" + vname + ".js");
337 window.V = vModule.VariantRules;
338 this.vr = new V(game.fen);
339 this.game = Object.assign({},
341 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
344 increment: tc.increment,
346 mycolor: [undefined,"w","b"][myIdx+1],
347 // opponent sid not strictly required, but easier
348 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
351 if (!!this.game.oppid)
353 // Send ping to server (answer pong if players[s] are connected)
354 this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid}));
358 return afterRetrival(game);
359 if (!!this.gameRef.rid)
361 this.st.conn.send(JSON.stringify({code:"askfullgame", target:this.gameRef.rid}));
362 // TODO: just send a game request message to the remote player,
363 // and when receiving answer just call loadGame(received_game)
364 // + remote peer should have registered us as an observer
365 // (send moves updates + resign/abort/draw actions)
369 GameStorage.get(this.gameRef.id, async (game) => {
370 afterRetrieval(game);
374 // Post-process a move (which was just played)
375 processMove: function(move) {
376 if (!this.game.mycolor)
377 return; //I'm just an observer
378 // Update storage (corr or live)
379 const colorIdx = ["w","b"].indexOf(move.color);
380 // https://stackoverflow.com/a/38750895
381 const allowed_fields = ["appear", "vanish", "start", "end"];
382 const filtered_move = Object.keys(move)
383 .filter(key => allowed_fields.includes(key))
384 .reduce((obj, key) => {
385 obj[key] = move[key];
388 // Send move ("newmove" event) to opponent(s) (if ours)
390 if (move.color == this.game.mycolor)
392 if (this.game.moves.length >= 2) //after first move
394 const elapsed = Date.now() - this.game.initime[colorIdx];
395 // elapsed time is measured in milliseconds
396 addTime = this.game.increment - elapsed/1000;
398 this.st.conn.send(JSON.stringify({
400 target: this.game.oppid,
401 move: Object.assign({}, filtered_move, {addTime: addTime}),
405 addTime = move.addTime; //supposed transmitted
406 const nextIdx = ["w","b"].indexOf(this.vr.turn);
407 GameStorage.update(this.gameRef.id,
411 clocks: this.game.clocks.map((t,i) => i==colorIdx
412 ? this.game.clocks[i] + addTime
413 : this.game.clocks[i]),
414 initime: this.game.initime.map((t,i) => i==nextIdx
416 : this.game.initime[i]),
418 // Also update current game object:
419 this.game.moves.push(move);
420 this.game.fen = move.fen;
421 //TODO: just this.game.clocks[colorIdx] += addTime;
422 this.$set(this.game.clocks, colorIdx, this.game.clocks[colorIdx] + addTime);
423 this.game.initime[nextIdx] = Date.now();
425 // TODO: this update function should also work for corr games
426 gameOver: function(score) {
427 this.game.mode = "analyze";
428 GameStorage.update(this.gameRef.id, { score: score });