Refactor endgame process, start working on game end (abort)
[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")
6dd02928 14 .button-group(v-if="game.mode!='analyze'")
a6088c90 15 button(@click="offerDraw") Draw
b988c726 16 button(@click="() => abortGame()") Abort
a6088c90 17 button(@click="resign") Resign
6dd02928 18 div(v-if="game.mode=='corr'")
4b0384fa 19 textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg")
a6088c90
BA
20 div(v-show="cursor>=0") {{ moves[cursor].message }}
21</template>
22
23<script>
46284a2f 24import BaseGame from "@/components/BaseGame.vue";
a6088c90
BA
25//import Chat from "@/components/Chat.vue";
26//import MoveList from "@/components/MoveList.vue";
27import { store } from "@/store";
d2634386 28import { GameStorage } from "@/utils/storage";
a6088c90
BA
29
30export default {
31 name: 'my-game',
32 components: {
33 BaseGame,
34 },
f7121527 35 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
36 data: function() {
37 return {
38 st: store.state,
4b0384fa
BA
39 gameRef: { //given in URL (rid = remote ID)
40 id: "",
41 rid: ""
42 },
43 game: { }, //passed to BaseGame
6dd02928 44 vr: null, //"variant rules" object initialized from FEN
93d1d7a7 45 drawOfferSent: false, //did I just ask for draw? (TODO: use for button style)
4b0384fa 46 people: [ ], //potential observers (TODO)
a6088c90
BA
47 };
48 },
49 watch: {
f7121527 50 '$route' (to, from) {
4fe5664d
BA
51 if (!!to.params["id"])
52 {
53 this.gameRef.id = to.params["id"];
54 this.gameRef.rid = to.query["rid"];
55 this.loadGame();
56 }
a6088c90
BA
57 },
58 },
a6088c90 59 created: function() {
f7121527 60 if (!!this.$route.params["id"])
a6088c90 61 {
f7121527
BA
62 this.gameRef.id = this.$route.params["id"];
63 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 64 this.loadGame();
f7121527 65 }
f7121527
BA
66 // TODO: how to know who is observing ? Send message to everyone with game ID ?
67 // and then just listen to (dis)connect events
3b450453
BA
68 // server always send "connect on " + URL ; then add to observers if game...
69 // detect multiple tabs connected (when connect ask server if my SID is already in use)
70// router when access a game page tell to server I joined + game ID (no need rid)
71// and ask server for current joined (= observers)
72// when send to chat (or a move), reach only this group (send gid along)
3b450453
BA
73 // --> doivent être enregistrés comme observers au niveau du serveur...
74 // non: poll users + events startObserving / stopObserving
b4fb1612 75 // (à faire au niveau du routeur ?)
3b450453 76
a6088c90
BA
77 // TODO: also handle "draw accepted" (use opponents array?)
78 // --> must give this info also when sending lastState...
79 // and, if all players agree then OK draw (end game ...etc)
80 const socketMessageListener = msg => {
81 const data = JSON.parse(msg.data);
82 let L = undefined;
83 switch (data.code)
84 {
f7121527 85 case "newmove":
c4f91d3f
BA
86 // NOTE: next call will trigger processMove()
87 this.$refs["basegame"].play(data.move,
88 "receive", this.game.vname!="Dark" ? "animate" : null);
a6088c90
BA
89 break;
90 case "pong": //received if we sent a ping (game still alive on our side)
91 if (this.gameRef.id != data.gameId)
f7121527 92 break; //games IDs don't match: the game is definitely over...
a6088c90
BA
93 this.oppConnected = true;
94 // Send our "last state" informations to opponent(s)
95 L = this.vr.moves.length;
96 Object.keys(this.opponents).forEach(oid => {
4b0384fa 97 this.st.conn.send(JSON.stringify({
a6088c90
BA
98 code: "lastate",
99 oppid: oid,
100 gameId: this.gameRef.id,
101 lastMove: (L>0?this.vr.moves[L-1]:undefined),
102 movesCount: L,
103 }));
104 });
105 break;
f7121527 106 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves
93d1d7a7 107 // TODO: need to send along clock state (my current time) with my last move
a6088c90
BA
108 case "lastate": //got opponent infos about last move
109 L = this.vr.moves.length;
110 if (this.gameRef.id != data.gameId)
111 break; //games IDs don't match: nothing we can do...
112 // OK, opponent still in game (which might be over)
113 if (this.score != "*")
114 {
115 // We finished the game (any result possible)
4b0384fa 116 this.st.conn.send(JSON.stringify({
a6088c90
BA
117 code: "lastate",
118 oppid: data.oppid,
119 gameId: this.gameRef.id,
120 score: this.score,
121 }));
122 }
123 else if (!!data.score) //opponent finished the game
124 this.endGame(data.score);
125 else if (data.movesCount < L)
126 {
127 // We must tell last move to opponent
4b0384fa 128 this.st.conn.send(JSON.stringify({
a6088c90
BA
129 code: "lastate",
130 oppid: this.opponent.id,
131 gameId: this.gameRef.id,
132 lastMove: this.vr.moves[L-1],
133 movesCount: L,
134 }));
135 }
136 else if (data.movesCount > L) //just got last move from him
c4f91d3f 137 this.play(data.lastMove, "animate"); //TODO: wrong call (3 args)
a6088c90 138 break;
93d1d7a7
BA
139 case "resign":
140 this.$refs["basegame"].endGame(
141 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
142 break;
143 case "timeover":
144 this.$refs["basegame"].endGame(
145 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
a6088c90 146 break;
93d1d7a7
BA
147 case "abort":
148 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
149 break;
150 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
151 // ==> on "newmove", check "drawOffer" field
a6088c90
BA
152 // TODO: also use (dis)connect info to count online players?
153 case "gameconnect":
154 case "gamedisconnect":
155 if (this.mode=="human")
156 {
157 const online = (data.code == "connect");
158 // If this is an opponent ?
159 if (!!this.opponents[data.id])
160 this.opponents[data.id].online = online;
161 else
162 {
163 // Or an observer ?
164 if (!online)
165 delete this.people[data.id];
166 else
167 this.people[data.id] = data.name;
168 }
169 }
170 break;
171 }
172 };
173 const socketCloseListener = () => {
4b0384fa
BA
174 this.st.conn.addEventListener('message', socketMessageListener);
175 this.st.conn.addEventListener('close', socketCloseListener);
a6088c90 176 };
4b0384fa
BA
177 this.st.conn.onmessage = socketMessageListener;
178 this.st.conn.onclose = socketCloseListener;
a6088c90
BA
179 },
180 // dans variant.js (plutôt room.js) conn gère aussi les challenges
181 // et les chats dans chat.js. Puis en webRTC, repenser tout ça.
182 methods: {
183 offerDraw: function() {
184 if (!confirm("Offer draw?"))
185 return;
186 // Stay in "draw offer sent" state until next move is played
187 this.drawOfferSent = true;
188 if (this.subMode == "corr")
189 {
190 // TODO: set drawOffer on in game (how ?)
191 }
192 else //live game
193 {
194 this.opponents.forEach(o => {
195 if (!!o.online)
196 {
197 try {
4b0384fa 198 this.st.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
a6088c90
BA
199 } catch (INVALID_STATE_ERR) {
200 return;
201 }
202 }
203 });
204 }
205 },
206 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
207 receiveDrawOffer: function() {
208 //if (...)
209 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
210 // if accept: send message "draw"
211 },
b988c726
BA
212 abortGame: function(event) {
213 if (!event)
214 {
215 // First call show options:
216 let modalBox = document.getElementById("modalAbort");
217 modalBox.checked = true;
218 }
219 else
220 {
221 console.log(event);
222 //const message = event.
223 this.gameOver("?");
224 this.game.players.forEach(p => {
225 if (!!p.sid && p.sid != this.st.user.sid)
226 {
227 this.st.conn.send(JSON.stringify({
228 code: "abort",
229 msg: message,
230 target: p.sid,
231 }));
232 }
233 });
234 }
a6088c90
BA
235 },
236 resign: function(e) {
237 if (!confirm("Resign the game?"))
238 return;
93d1d7a7
BA
239 this.game.players.forEach(p => {
240 if (!!p.sid && p.sid != this.st.user.sid)
241 {
242 this.st.conn.send(JSON.stringify({
243 code: "resign",
244 target: p.sid,
245 }));
a6088c90 246 }
93d1d7a7
BA
247 });
248 // Next line will trigger a "gameover" event, bubbling up till here
249 this.$refs["basegame"].endGame(this.game.mycolor=="w" ? "0-1" : "1-0");
a6088c90 250 },
b196f8ea
BA
251 // 4 cases for loading a game:
252 // - from localStorage (one running game I play)
253 // - from indexedDB (one completed live game)
254 // - from server (one correspondance game I play[ed] or not)
255 // - from remote peer (one live game I don't play, finished or not)
6dd02928
BA
256 loadGame: function() {
257 GameStorage.get(this.gameRef, async (game) => {
4b0384fa
BA
258 this.game = Object.assign({},
259 game,
260 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
b4fb1612
BA
261 {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
262 p => p.sid == this.st.user.sid)]},
4b0384fa 263 );
6dd02928 264 const vModule = await import("@/variants/" + game.vname + ".js");
d6c1bf37 265 window.V = vModule.VariantRules;
6dd02928 266 this.vr = new V(game.fen);
6274a545
BA
267 // Post-processing: decorate each move with current FEN:
268 // (to be able to jump to any position quickly)
269 game.moves.forEach(move => {
c4f91d3f
BA
270 // NOTE: this is doing manually what BaseGame.play() achieve...
271 // but in a lighter "fast-forward" way
9d54ab89 272 move.color = this.vr.turn;
8a7452b5 273 this.vr.play(move);
9d54ab89 274 move.fen = this.vr.getFen();
6274a545
BA
275 });
276 this.vr.re_init(game.fen);
d6c1bf37 277 });
4fe5664d
BA
278// // Poll all players except me (if I'm playing) to know online status.
279// // --> Send ping to server (answer pong if players[s] are connected)
280// if (this.gameInfo.players.some(p => p.sid == this.st.user.sid))
281// {
282// this.game.players.forEach(p => {
283// if (p.sid != this.st.user.sid)
284// this.st.conn.send(JSON.stringify({code:"ping", oppid:p.sid}));
285// });
286// }
a6088c90 287 },
b4fb1612 288 // TODO: refactor this old "oppConnected" logic
6ec161b9
BA
289// oppConnected: function(uid) {
290// return this.opponents.some(o => o.id == uid && o.online);
291// },
9d54ab89 292 // Post-process a move (which was just played)
ce87ac6a 293 processMove: function(move) {
b4fb1612
BA
294 if (!this.game.mycolor)
295 return; //I'm just an observer
9d54ab89 296 // Update storage (corr or live)
c4f91d3f 297 const colorIdx = ["w","b","g","r"].indexOf(move.color);
9d54ab89
BA
298 // https://stackoverflow.com/a/38750895
299 const allowed_fields = ["appear", "vanish", "start", "end"];
300 const filtered_move = Object.keys(move)
301 .filter(key => allowed_fields.includes(key))
302 .reduce((obj, key) => {
8a7452b5 303 obj[key] = move[key];
9d54ab89
BA
304 return obj;
305 }, {});
b4fb1612 306 // Send move ("newmove" event) to opponent(s) (if ours)
9d54ab89 307 // (otherwise move.elapsed is supposed to be already transmitted)
c4f91d3f 308 let addTime = undefined;
9d54ab89 309 if (move.color == this.game.mycolor)
b4fb1612 310 {
9d54ab89 311 const elapsed = Date.now() - GameStorage.getInitime();
b4fb1612
BA
312 this.game.players.forEach(p => {
313 if (p.sid != this.st.user.sid)
93d1d7a7 314 {
8a7452b5
BA
315 this.st.conn.send(JSON.stringify({
316 code: "newmove",
9d54ab89
BA
317 target: p.sid,
318 move: Object.assign({}, filtered_move, {elapsed: elapsed}),
8a7452b5 319 }));
93d1d7a7 320 }
b4fb1612 321 });
9d54ab89 322 move.elapsed = elapsed;
c4f91d3f
BA
323 // elapsed time is measured in milliseconds
324 addTime = this.game.increment - elapsed/1000;
b4fb1612 325 }
9d54ab89
BA
326 GameStorage.update({
327 colorIdx: colorIdx,
328 move: filtered_move,
329 fen: move.fen,
c4f91d3f
BA
330 addTime: addTime,
331 initime: (this.vr.turn == this.game.mycolor), //my turn now?
9d54ab89 332 });
b4fb1612 333 },
93d1d7a7 334 // TODO: this update function should also work for corr games
b4fb1612 335 gameOver: function(score) {
93d1d7a7 336 this.game.mode = "analyze";
9d54ab89
BA
337 GameStorage.update({
338 score: score,
339 });
ce87ac6a 340 },
a6088c90
BA
341 },
342};
343</script>