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: show players names + clocks state
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 import BaseGame from "@/components/BaseGame.vue";
27 //import Chat from "@/components/Chat.vue";
28 //import MoveList from "@/components/MoveList.vue";
29 import { store } from "@/store";
30 import { GameStorage } from "@/utils/gameStorage";
31 import { ppt } from "@/utils/datetime";
38 // gameRef: to find the game in (potentially remote) storage
42 gameRef: { //given in URL (rid = remote ID)
46 game: { }, //passed to BaseGame
47 virtualClocks: [0, 0], //initialized with true game.clocks
48 vr: null, //"variant rules" object initialized from FEN
49 drawOfferSent: false, //did I just ask for draw? (TODO: use for button style)
50 people: [ ], //potential observers (TODO)
55 if (!!to.params["id"])
57 this.gameRef.id = to.params["id"];
58 this.gameRef.rid = to.query["rid"];
62 "game.clocks": function(newState) {
63 this.virtualClocks = newState.map(s => ppt(s));
64 const currentTurn = this.vr.turn;
65 const colorIdx = ["w","b","g","r"].indexOf(currentTurn);
66 let countdown = newState[colorIdx] -
67 (Date.now() - this.game.initime[colorIdx])/1000;
68 const myTurn = (currentTurn == this.game.mycolor);
70 console.log(this.vr.turn + " " + currentTurn + " " + this.vr.getFen());
72 let clockUpdate = setInterval(() => {
77 console.log(countdown);
78 console.log(this.vr.turn +" " + currentTurn + " " + this.vr.getFen());
80 // TODO: incoherent state because vr is altered in BaseGame to replay game
81 // ==> should use a temporary vr ?
85 if (countdown <= 0 || this.vr.turn != currentTurn)
87 clearInterval(clockUpdate);
88 if (countdown <= 0 && myTurn)
90 this.$refs["basegame"].endGame(
91 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
92 this.game.players.forEach(p => {
93 if (p.sid != this.st.user.sid)
95 this.st.conn.send(JSON.stringify({
103 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
104 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
108 created: function() {
109 if (!!this.$route.params["id"])
111 this.gameRef.id = this.$route.params["id"];
112 this.gameRef.rid = this.$route.query["rid"];
115 // TODO: how to know who is observing ? Send message to everyone with game ID ?
116 // and then just listen to (dis)connect events
117 // server always send "connect on " + URL ; then add to observers if game...
118 // detect multiple tabs connected (when connect ask server if my SID is already in use)
119 // router when access a game page tell to server I joined + game ID (no need rid)
120 // and ask server for current joined (= observers)
121 // when send to chat (or a move), reach only this group (send gid along)
122 // --> doivent être enregistrés comme observers au niveau du serveur...
123 // non: poll users + events startObserving / stopObserving
124 // (à faire au niveau du routeur ?)
126 // TODO: also handle "draw accepted" (use opponents array?)
127 // --> must give this info also when sending lastState...
128 // and, if all players agree then OK draw (end game ...etc)
129 const socketMessageListener = msg => {
130 const data = JSON.parse(msg.data);
135 // NOTE: next call will trigger processMove()
136 this.$refs["basegame"].play(data.move,
137 "receive", this.game.vname!="Dark" ? "animate" : null);
139 case "pong": //received if we sent a ping (game still alive on our side)
140 if (this.gameRef.id != data.gameId)
141 break; //games IDs don't match: the game is definitely over...
142 this.oppConnected = true;
143 // Send our "last state" informations to opponent(s)
144 L = this.vr.moves.length;
145 Object.keys(this.opponents).forEach(oid => {
146 this.st.conn.send(JSON.stringify({
149 gameId: this.gameRef.id,
150 lastMove: (L>0?this.vr.moves[L-1]:undefined),
155 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves
156 // TODO: need to send along clock state (my current time) with my last move
157 case "lastate": //got opponent infos about last move
158 L = this.vr.moves.length;
159 if (this.gameRef.id != data.gameId)
160 break; //games IDs don't match: nothing we can do...
161 // OK, opponent still in game (which might be over)
162 if (this.score != "*")
164 // We finished the game (any result possible)
165 this.st.conn.send(JSON.stringify({
168 gameId: this.gameRef.id,
172 else if (!!data.score) //opponent finished the game
173 this.endGame(data.score);
174 else if (data.movesCount < L)
176 // We must tell last move to opponent
177 this.st.conn.send(JSON.stringify({
179 oppid: this.opponent.id,
180 gameId: this.gameRef.id,
181 lastMove: this.vr.moves[L-1],
185 else if (data.movesCount > L) //just got last move from him
186 this.play(data.lastMove, "animate"); //TODO: wrong call (3 args)
189 this.$refs["basegame"].endGame(
190 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
193 this.$refs["basegame"].endGame(
194 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
197 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
199 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
200 // ==> on "newmove", check "drawOffer" field
201 // TODO: also use (dis)connect info to count online players?
203 case "gamedisconnect":
204 if (this.mode=="human")
206 const online = (data.code == "connect");
207 // If this is an opponent ?
208 if (!!this.opponents[data.id])
209 this.opponents[data.id].online = online;
214 delete this.people[data.id];
216 this.people[data.id] = data.name;
222 const socketCloseListener = () => {
223 this.st.conn.addEventListener('message', socketMessageListener);
224 this.st.conn.addEventListener('close', socketCloseListener);
226 this.st.conn.onmessage = socketMessageListener;
227 this.st.conn.onclose = socketCloseListener;
229 // dans variant.js (plutôt room.js) conn gère aussi les challenges
230 // et les chats dans chat.js. Puis en webRTC, repenser tout ça.
232 offerDraw: function() {
233 if (!confirm("Offer draw?"))
235 // Stay in "draw offer sent" state until next move is played
236 this.drawOfferSent = true;
237 if (this.subMode == "corr")
239 // TODO: set drawOffer on in game (how ?)
243 this.opponents.forEach(o => {
247 this.st.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
248 } catch (INVALID_STATE_ERR) {
255 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
256 receiveDrawOffer: function() {
258 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
259 // if accept: send message "draw"
261 abortGame: function(event) {
264 // First call show options:
265 let modalBox = document.getElementById("modalAbort");
266 modalBox.checked = true;
272 //const message = event.
273 // Next line will trigger a "gameover" event, bubbling up till here
274 this.$refs["basegame"].endGame("?", "Abort: " + event.msg); //TODO
275 this.game.players.forEach(p => {
276 if (!!p.sid && p.sid != this.st.user.sid)
278 this.st.conn.send(JSON.stringify({
287 resign: function(e) {
288 if (!confirm("Resign the game?"))
290 this.game.players.forEach(p => {
291 if (!!p.sid && p.sid != this.st.user.sid)
293 this.st.conn.send(JSON.stringify({
299 // Next line will trigger a "gameover" event, bubbling up till here
300 this.$refs["basegame"].endGame(
301 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
303 // 3 cases for loading a game:
304 // - from indexedDB (running or completed live game I play)
305 // - from server (one correspondance game I play[ed] or not)
306 // - from remote peer (one live game I don't play, finished or not)
307 loadGame: function(game) {
308 const afterRetrieval = async (game) => {
309 const vModule = await import("@/variants/" + game.vname + ".js");
310 window.V = vModule.VariantRules;
311 this.vr = new V(game.fen);
312 this.game = Object.assign({},
314 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
315 {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
316 p => p.sid == this.st.user.sid)]},
320 return afterRetrival(game);
321 if (!!this.gameRef.rid)
323 // TODO: just send a game request message to the remote player,
324 // and when receiving answer just call loadGame(received_game)
325 // + remote peer should have registered us as an observer
326 // (send moves updates + resign/abort/draw actions)
331 GameStorage.get(this.gameRef.id, async (game) => {
332 afterRetrieval(game);
335 // // Poll all players except me (if I'm playing) to know online status.
336 // // --> Send ping to server (answer pong if players[s] are connected)
337 // if (this.gameInfo.players.some(p => p.sid == this.st.user.sid))
339 // this.game.players.forEach(p => {
340 // if (p.sid != this.st.user.sid)
341 // this.st.conn.send(JSON.stringify({code:"ping", oppid:p.sid}));
345 // TODO: refactor this old "oppConnected" logic
346 // oppConnected: function(uid) {
347 // return this.opponents.some(o => o.id == uid && o.online);
349 // Post-process a move (which was just played)
350 processMove: function(move) {
351 if (!this.game.mycolor)
352 return; //I'm just an observer
353 // Update storage (corr or live)
354 const colorIdx = ["w","b","g","r"].indexOf(move.color);
355 // https://stackoverflow.com/a/38750895
356 const allowed_fields = ["appear", "vanish", "start", "end"];
357 const filtered_move = Object.keys(move)
358 .filter(key => allowed_fields.includes(key))
359 .reduce((obj, key) => {
360 obj[key] = move[key];
363 // Send move ("newmove" event) to opponent(s) (if ours)
364 let addTime = undefined;
365 if (move.color == this.game.mycolor)
367 const elapsed = Date.now() - this.game.initime[colorIdx];
368 // elapsed time is measured in milliseconds
369 addTime = this.game.increment - elapsed/1000;
370 this.game.players.forEach(p => {
371 if (p.sid != this.st.user.sid)
373 this.st.conn.send(JSON.stringify({
376 move: Object.assign({}, filtered_move, {addTime: addTime}),
382 addTime = move.addTime; //supposed transmitted
383 const nextIdx = ["w","b","g","r"].indexOf(this.vr.turn);
384 GameStorage.update(this.gameRef.id,
392 // Also update current game object:
393 this.game.moves.push(move);
394 this.game.fen = move.fen;
395 this.game.clocks[colorIdx] += (!!addTime ? addTime : 0);
396 this.game.initime[nextIdx] = Date.now();
398 // TODO: this update function should also work for corr games
399 gameOver: function(score) {
400 this.game.mode = "analyze";
401 GameStorage.update(this.gameRef.id,