Implement abort logic - add some TODOs (no 3 or 4 players games anymore)
[vchess.git] / client / src / views / Game.vue
1 <template lang="pug">
2 .row
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 }}
23 </template>
24
25 <!--
26 // TODO: movelist dans basegame et chat ici
27 // se limiter à 2 joueurs pour l'instant au moins tout en restant général
28 // ==> après, implémenter/vérifier les passages de challenges + parties en cours
29 // observer,
30 // + problèmes, habiller et publier. (+ corr...)
31
32 // refactor players.forEach(...) into sendTo(opponent, ...)
33 -->
34
35 <script>
36 import BaseGame from "@/components/BaseGame.vue";
37 //import Chat from "@/components/Chat.vue";
38 //import MoveList from "@/components/MoveList.vue";
39 import { store } from "@/store";
40 import { GameStorage } from "@/utils/gameStorage";
41 import { ppt } from "@/utils/datetime";
42
43 export default {
44 name: 'my-game',
45 components: {
46 BaseGame,
47 },
48 // gameRef: to find the game in (potentially remote) storage
49 data: function() {
50 return {
51 st: store.state,
52 gameRef: { //given in URL (rid = remote ID)
53 id: "",
54 rid: ""
55 },
56 game: { }, //passed to BaseGame
57 virtualClocks: [0, 0], //initialized with true game.clocks
58 vr: null, //"variant rules" object initialized from FEN
59 drawOfferSent: false, //did I just ask for draw? (TODO: use for button style)
60 people: [ ], //potential observers (TODO)
61 };
62 },
63 watch: {
64 '$route' (to, from) {
65 if (!!to.params["id"])
66 {
67 this.gameRef.id = to.params["id"];
68 this.gameRef.rid = to.query["rid"];
69 this.loadGame();
70 }
71 },
72 "game.clocks": function(newState) {
73 this.virtualClocks = newState.map(s => ppt(s));
74 const currentTurn = this.vr.turn;
75 const colorIdx = ["w","b","g","r"].indexOf(currentTurn);
76 let countdown = newState[colorIdx] -
77 (Date.now() - this.game.initime[colorIdx])/1000;
78 const myTurn = (currentTurn == this.game.mycolor);
79 let clockUpdate = setInterval(() => {
80 if (countdown <= 0 || this.vr.turn != currentTurn)
81 {
82 clearInterval(clockUpdate);
83 if (countdown <= 0 && myTurn)
84 {
85 this.$refs["basegame"].endGame(
86 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
87 this.game.players.forEach(p => {
88 if (p.sid != this.st.user.sid)
89 {
90 this.st.conn.send(JSON.stringify({
91 code: "timeover",
92 target: p.sid,
93 }));
94 }
95 });
96 }
97 }
98 else
99 {
100 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
101 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
102 }
103 }, 1000);
104 },
105 },
106 created: function() {
107 if (!!this.$route.params["id"])
108 {
109 this.gameRef.id = this.$route.params["id"];
110 this.gameRef.rid = this.$route.query["rid"];
111 this.loadGame();
112 }
113 // TODO: how to know who is observing ? Send message to everyone with game ID ?
114 // and then just listen to (dis)connect events
115 // server always send "connect on " + URL ; then add to observers if game...
116 // detect multiple tabs connected (when connect ask server if my SID is already in use)
117 // router when access a game page tell to server I joined + game ID (no need rid)
118 // and ask server for current joined (= observers)
119 // when send to chat (or a move), reach only this group (send gid along)
120 // --> doivent être enregistrés comme observers au niveau du serveur...
121 // non: poll users + events startObserving / stopObserving
122 // (à faire au niveau du routeur ?)
123
124 // TODO: also handle "draw accepted" (use opponents array?)
125 // --> must give this info also when sending lastState...
126 // and, if all players agree then OK draw (end game ...etc)
127 const socketMessageListener = msg => {
128 const data = JSON.parse(msg.data);
129 let L = undefined;
130 switch (data.code)
131 {
132 case "newmove":
133 // NOTE: next call will trigger processMove()
134 this.$refs["basegame"].play(data.move,
135 "receive", this.game.vname!="Dark" ? "animate" : null);
136 break;
137 case "pong": //received if we sent a ping (game still alive on our side)
138 if (this.gameRef.id != data.gameId)
139 break; //games IDs don't match: the game is definitely over...
140 this.oppConnected = true;
141 // Send our "last state" informations to opponent(s)
142 L = this.vr.moves.length;
143 Object.keys(this.opponents).forEach(oid => {
144 this.st.conn.send(JSON.stringify({
145 code: "lastate",
146 oppid: oid,
147 gameId: this.gameRef.id,
148 lastMove: (L>0?this.vr.moves[L-1]:undefined),
149 movesCount: L,
150 }));
151 });
152 break;
153 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves
154 // TODO: need to send along clock state (my current time) with my last move
155 case "lastate": //got opponent infos about last move
156 L = this.vr.moves.length;
157 if (this.gameRef.id != data.gameId)
158 break; //games IDs don't match: nothing we can do...
159 // OK, opponent still in game (which might be over)
160 if (this.score != "*")
161 {
162 // We finished the game (any result possible)
163 this.st.conn.send(JSON.stringify({
164 code: "lastate",
165 oppid: data.oppid,
166 gameId: this.gameRef.id,
167 score: this.score,
168 }));
169 }
170 else if (!!data.score) //opponent finished the game
171 this.endGame(data.score);
172 else if (data.movesCount < L)
173 {
174 // We must tell last move to opponent
175 this.st.conn.send(JSON.stringify({
176 code: "lastate",
177 oppid: this.opponent.id,
178 gameId: this.gameRef.id,
179 lastMove: this.vr.moves[L-1],
180 movesCount: L,
181 }));
182 }
183 else if (data.movesCount > L) //just got last move from him
184 this.play(data.lastMove, "animate"); //TODO: wrong call (3 args)
185 break;
186 case "resign":
187 this.$refs["basegame"].endGame(
188 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
189 break;
190 case "timeover":
191 this.$refs["basegame"].endGame(
192 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
193 break;
194 case "abort":
195 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
196 break;
197 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
198 // ==> on "newmove", check "drawOffer" field
199 // TODO: also use (dis)connect info to count online players?
200 case "gameconnect":
201 case "gamedisconnect":
202 if (this.mode=="human")
203 {
204 const online = (data.code == "connect");
205 // If this is an opponent ?
206 if (!!this.opponents[data.id])
207 this.opponents[data.id].online = online;
208 else
209 {
210 // Or an observer ?
211 if (!online)
212 delete this.people[data.id];
213 else
214 this.people[data.id] = data.name;
215 }
216 }
217 break;
218 }
219 };
220 const socketCloseListener = () => {
221 this.st.conn.addEventListener('message', socketMessageListener);
222 this.st.conn.addEventListener('close', socketCloseListener);
223 };
224 this.st.conn.onmessage = socketMessageListener;
225 this.st.conn.onclose = socketCloseListener;
226 },
227 // dans variant.js (plutôt room.js) conn gère aussi les challenges
228 // et les chats dans chat.js. Puis en webRTC, repenser tout ça.
229 methods: {
230 offerDraw: function() {
231 if (!confirm("Offer draw?"))
232 return;
233 // Stay in "draw offer sent" state until next move is played
234 this.drawOfferSent = true;
235 if (this.subMode == "corr")
236 {
237 // TODO: set drawOffer on in game (how ?)
238 }
239 else //live game
240 {
241 this.opponents.forEach(o => {
242 if (!!o.online)
243 {
244 try {
245 this.st.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
246 } catch (INVALID_STATE_ERR) {
247 return;
248 }
249 }
250 });
251 }
252 },
253 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
254 receiveDrawOffer: function() {
255 //if (...)
256 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
257 // if accept: send message "draw"
258 },
259 abortGame: function(event) {
260 let modalBox = document.getElementById("modalAbort");
261 if (!event)
262 {
263 // First call show options:
264 modalBox.checked = true;
265 }
266 else
267 {
268 modalBox.checked = false; //decision made: box disappear
269 const message = event.target.innerText;
270 // Next line will trigger a "gameover" event, bubbling up till here
271 this.$refs["basegame"].endGame("?", "Abort: " + message);
272 this.game.players.forEach(p => {
273 if (!!p.sid && p.sid != this.st.user.sid)
274 {
275 this.st.conn.send(JSON.stringify({
276 code: "abort",
277 msg: message,
278 target: p.sid,
279 }));
280 }
281 });
282 }
283 },
284 resign: function(e) {
285 if (!confirm("Resign the game?"))
286 return;
287 this.game.players.forEach(p => {
288 if (!!p.sid && p.sid != this.st.user.sid)
289 {
290 this.st.conn.send(JSON.stringify({
291 code: "resign",
292 target: p.sid,
293 }));
294 }
295 });
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");
299 },
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 const vModule = await import("@/variants/" + game.vname + ".js");
307 window.V = vModule.VariantRules;
308 this.vr = new V(game.fen);
309 this.game = Object.assign({},
310 game,
311 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
312 {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
313 p => p.sid == this.st.user.sid)]},
314 );
315 };
316 if (!!game)
317 return afterRetrival(game);
318 if (!!this.gameRef.rid)
319 {
320 // TODO: just send a game request message to the remote player,
321 // and when receiving answer just call loadGame(received_game)
322 // + remote peer should have registered us as an observer
323 // (send moves updates + resign/abort/draw actions)
324 return;
325 }
326 else
327 {
328 GameStorage.get(this.gameRef.id, async (game) => {
329 afterRetrieval(game);
330 });
331 }
332 // // Poll all players except me (if I'm playing) to know online status.
333 // // --> Send ping to server (answer pong if players[s] are connected)
334 // if (this.gameInfo.players.some(p => p.sid == this.st.user.sid))
335 // {
336 // this.game.players.forEach(p => {
337 // if (p.sid != this.st.user.sid)
338 // this.st.conn.send(JSON.stringify({code:"ping", oppid:p.sid}));
339 // });
340 // }
341 },
342 // TODO: refactor this old "oppConnected" logic
343 // oppConnected: function(uid) {
344 // return this.opponents.some(o => o.id == uid && o.online);
345 // },
346 // Post-process a move (which was just played)
347 processMove: function(move) {
348 if (!this.game.mycolor)
349 return; //I'm just an observer
350 // Update storage (corr or live)
351 const colorIdx = ["w","b","g","r"].indexOf(move.color);
352 // https://stackoverflow.com/a/38750895
353 const allowed_fields = ["appear", "vanish", "start", "end"];
354 const filtered_move = Object.keys(move)
355 .filter(key => allowed_fields.includes(key))
356 .reduce((obj, key) => {
357 obj[key] = move[key];
358 return obj;
359 }, {});
360 // Send move ("newmove" event) to opponent(s) (if ours)
361 let addTime = undefined;
362 if (move.color == this.game.mycolor)
363 {
364 const elapsed = Date.now() - this.game.initime[colorIdx];
365 // elapsed time is measured in milliseconds
366 addTime = this.game.increment - elapsed/1000;
367 this.game.players.forEach(p => {
368 if (p.sid != this.st.user.sid)
369 {
370 this.st.conn.send(JSON.stringify({
371 code: "newmove",
372 target: p.sid,
373 move: Object.assign({}, filtered_move, {addTime: addTime}),
374 }));
375 }
376 });
377 }
378 else
379 addTime = move.addTime; //supposed transmitted
380 const nextIdx = ["w","b","g","r"].indexOf(this.vr.turn);
381 GameStorage.update(this.gameRef.id,
382 {
383 colorIdx: colorIdx,
384 nextIdx: nextIdx,
385 move: filtered_move,
386 fen: move.fen,
387 addTime: addTime,
388 });
389 // Also update current game object:
390 this.game.moves.push(move);
391 this.game.fen = move.fen;
392 //TODO: just this.game.clocks[colorIdx] += (!!addTime ? addTime : 0);
393 this.$set(this.game.clocks, colorIdx,
394 this.game.clocks[colorIdx] + (!!addTime ? addTime : 0));
395 this.game.initime[nextIdx] = Date.now();
396 },
397 // TODO: this update function should also work for corr games
398 gameOver: function(score) {
399 this.game.mode = "analyze";
400 GameStorage.update(this.gameRef.id,
401 {
402 score: score,
403 });
404 },
405 },
406 };
407 </script>