Implement abort logic - add some TODOs (no 3 or 4 players games anymore)
[vchess.git] / client / src / views / Game.vue
CommitLineData
a6088c90
BA
1<template lang="pug">
2.row
3 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
b988c726
BA
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"] }}
b4fb1612
BA
12 BaseGame(:game="game" :vr="vr" ref="basegame"
13 @newmove="processMove" @gameover="gameOver")
809ba2aa
BA
14 // TODO: show players names + clocks state
15 div Time: {{ virtualClocks[0] }} - {{ virtualClocks[1] }}
d4036efe 16 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
a6088c90 17 button(@click="offerDraw") Draw
b988c726 18 button(@click="() => abortGame()") Abort
a6088c90 19 button(@click="resign") Resign
6dd02928 20 div(v-if="game.mode=='corr'")
4b0384fa 21 textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg")
a6088c90
BA
22 div(v-show="cursor>=0") {{ moves[cursor].message }}
23</template>
24
9aa229f3
BA
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
a6088c90 35<script>
46284a2f 36import BaseGame from "@/components/BaseGame.vue";
a6088c90
BA
37//import Chat from "@/components/Chat.vue";
38//import MoveList from "@/components/MoveList.vue";
39import { store } from "@/store";
967a2686 40import { GameStorage } from "@/utils/gameStorage";
5b87454c 41import { ppt } from "@/utils/datetime";
a6088c90
BA
42
43export default {
44 name: 'my-game',
45 components: {
46 BaseGame,
47 },
f7121527 48 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
49 data: function() {
50 return {
51 st: store.state,
4b0384fa
BA
52 gameRef: { //given in URL (rid = remote ID)
53 id: "",
54 rid: ""
55 },
56 game: { }, //passed to BaseGame
809ba2aa 57 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 58 vr: null, //"variant rules" object initialized from FEN
93d1d7a7 59 drawOfferSent: false, //did I just ask for draw? (TODO: use for button style)
4b0384fa 60 people: [ ], //potential observers (TODO)
a6088c90
BA
61 };
62 },
63 watch: {
f7121527 64 '$route' (to, from) {
4fe5664d
BA
65 if (!!to.params["id"])
66 {
67 this.gameRef.id = to.params["id"];
68 this.gameRef.rid = to.query["rid"];
69 this.loadGame();
70 }
a6088c90 71 },
5b87454c 72 "game.clocks": function(newState) {
809ba2aa
BA
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);
809ba2aa 79 let clockUpdate = setInterval(() => {
809ba2aa
BA
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 }
9aa229f3
BA
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 }
809ba2aa 103 }, 1000);
5b87454c 104 },
a6088c90 105 },
a6088c90 106 created: function() {
f7121527 107 if (!!this.$route.params["id"])
a6088c90 108 {
f7121527
BA
109 this.gameRef.id = this.$route.params["id"];
110 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 111 this.loadGame();
f7121527 112 }
f7121527
BA
113 // TODO: how to know who is observing ? Send message to everyone with game ID ?
114 // and then just listen to (dis)connect events
3b450453
BA
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)
3b450453
BA
120 // --> doivent être enregistrés comme observers au niveau du serveur...
121 // non: poll users + events startObserving / stopObserving
b4fb1612 122 // (à faire au niveau du routeur ?)
3b450453 123
a6088c90
BA
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 {
f7121527 132 case "newmove":
c4f91d3f
BA
133 // NOTE: next call will trigger processMove()
134 this.$refs["basegame"].play(data.move,
135 "receive", this.game.vname!="Dark" ? "animate" : null);
a6088c90
BA
136 break;
137 case "pong": //received if we sent a ping (game still alive on our side)
138 if (this.gameRef.id != data.gameId)
f7121527 139 break; //games IDs don't match: the game is definitely over...
a6088c90
BA
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 => {
4b0384fa 144 this.st.conn.send(JSON.stringify({
a6088c90
BA
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;
f7121527 153 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves
93d1d7a7 154 // TODO: need to send along clock state (my current time) with my last move
a6088c90
BA
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)
4b0384fa 163 this.st.conn.send(JSON.stringify({
a6088c90
BA
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
4b0384fa 175 this.st.conn.send(JSON.stringify({
a6088c90
BA
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
c4f91d3f 184 this.play(data.lastMove, "animate"); //TODO: wrong call (3 args)
a6088c90 185 break;
93d1d7a7
BA
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");
a6088c90 193 break;
93d1d7a7
BA
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
a6088c90
BA
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 = () => {
4b0384fa
BA
221 this.st.conn.addEventListener('message', socketMessageListener);
222 this.st.conn.addEventListener('close', socketCloseListener);
a6088c90 223 };
4b0384fa
BA
224 this.st.conn.onmessage = socketMessageListener;
225 this.st.conn.onclose = socketCloseListener;
a6088c90
BA
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 {
4b0384fa 245 this.st.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
a6088c90
BA
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 },
b988c726 259 abortGame: function(event) {
9aa229f3 260 let modalBox = document.getElementById("modalAbort");
b988c726
BA
261 if (!event)
262 {
263 // First call show options:
b988c726
BA
264 modalBox.checked = true;
265 }
266 else
267 {
9aa229f3
BA
268 modalBox.checked = false; //decision made: box disappear
269 const message = event.target.innerText;
d4036efe 270 // Next line will trigger a "gameover" event, bubbling up till here
9aa229f3 271 this.$refs["basegame"].endGame("?", "Abort: " + message);
b988c726
BA
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 }
a6088c90
BA
283 },
284 resign: function(e) {
285 if (!confirm("Resign the game?"))
286 return;
93d1d7a7
BA
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 }));
a6088c90 294 }
93d1d7a7
BA
295 });
296 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
297 this.$refs["basegame"].endGame(
298 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 299 },
967a2686
BA
300 // 3 cases for loading a game:
301 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
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)
967a2686
BA
304 loadGame: function(game) {
305 const afterRetrieval = async (game) => {
d4036efe
BA
306 const vModule = await import("@/variants/" + game.vname + ".js");
307 window.V = vModule.VariantRules;
809ba2aa 308 this.vr = new V(game.fen);
4b0384fa
BA
309 this.game = Object.assign({},
310 game,
311 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
b4fb1612
BA
312 {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
313 p => p.sid == this.st.user.sid)]},
4b0384fa 314 );
967a2686
BA
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 }
4fe5664d
BA
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// }
a6088c90 341 },
b4fb1612 342 // TODO: refactor this old "oppConnected" logic
6ec161b9
BA
343// oppConnected: function(uid) {
344// return this.opponents.some(o => o.id == uid && o.online);
345// },
9d54ab89 346 // Post-process a move (which was just played)
ce87ac6a 347 processMove: function(move) {
b4fb1612
BA
348 if (!this.game.mycolor)
349 return; //I'm just an observer
9d54ab89 350 // Update storage (corr or live)
c4f91d3f 351 const colorIdx = ["w","b","g","r"].indexOf(move.color);
9d54ab89
BA
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) => {
8a7452b5 357 obj[key] = move[key];
9d54ab89
BA
358 return obj;
359 }, {});
b4fb1612 360 // Send move ("newmove" event) to opponent(s) (if ours)
c4f91d3f 361 let addTime = undefined;
9d54ab89 362 if (move.color == this.game.mycolor)
b4fb1612 363 {
809ba2aa 364 const elapsed = Date.now() - this.game.initime[colorIdx];
5b87454c
BA
365 // elapsed time is measured in milliseconds
366 addTime = this.game.increment - elapsed/1000;
b4fb1612
BA
367 this.game.players.forEach(p => {
368 if (p.sid != this.st.user.sid)
93d1d7a7 369 {
8a7452b5
BA
370 this.st.conn.send(JSON.stringify({
371 code: "newmove",
9d54ab89 372 target: p.sid,
5b87454c 373 move: Object.assign({}, filtered_move, {addTime: addTime}),
8a7452b5 374 }));
93d1d7a7 375 }
b4fb1612
BA
376 });
377 }
5b87454c
BA
378 else
379 addTime = move.addTime; //supposed transmitted
809ba2aa 380 const nextIdx = ["w","b","g","r"].indexOf(this.vr.turn);
967a2686
BA
381 GameStorage.update(this.gameRef.id,
382 {
9d54ab89 383 colorIdx: colorIdx,
809ba2aa 384 nextIdx: nextIdx,
9d54ab89
BA
385 move: filtered_move,
386 fen: move.fen,
c4f91d3f 387 addTime: addTime,
9d54ab89 388 });
967a2686
BA
389 // Also update current game object:
390 this.game.moves.push(move);
391 this.game.fen = move.fen;
27d18a24
BA
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));
809ba2aa 395 this.game.initime[nextIdx] = Date.now();
b4fb1612 396 },
93d1d7a7 397 // TODO: this update function should also work for corr games
b4fb1612 398 gameOver: function(score) {
93d1d7a7 399 this.game.mode = "analyze";
5b87454c
BA
400 GameStorage.update(this.gameRef.id,
401 {
9d54ab89
BA
402 score: score,
403 });
ce87ac6a 404 },
a6088c90
BA
405 },
406};
407</script>