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