'update'
[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
b4fb1612
BA
4 BaseGame(:game="game" :vr="vr" ref="basegame"
5 @newmove="processMove" @gameover="gameOver")
6dd02928 6 .button-group(v-if="game.mode!='analyze'")
a6088c90
BA
7 button(@click="offerDraw") Draw
8 button(@click="abortGame") Abort
9 button(@click="resign") Resign
6dd02928 10 div(v-if="game.mode=='corr'")
4b0384fa 11 textarea(v-show="score=='*' && vr.turn==game.mycolor" v-model="corrMsg")
a6088c90
BA
12 div(v-show="cursor>=0") {{ moves[cursor].message }}
13</template>
14
15<script>
46284a2f 16import BaseGame from "@/components/BaseGame.vue";
a6088c90
BA
17//import Chat from "@/components/Chat.vue";
18//import MoveList from "@/components/MoveList.vue";
19import { store } from "@/store";
d2634386 20import { GameStorage } from "@/utils/storage";
a6088c90
BA
21
22export default {
23 name: 'my-game',
24 components: {
25 BaseGame,
26 },
f7121527 27 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
28 data: function() {
29 return {
30 st: store.state,
4b0384fa
BA
31 gameRef: { //given in URL (rid = remote ID)
32 id: "",
33 rid: ""
34 },
35 game: { }, //passed to BaseGame
6dd02928 36 vr: null, //"variant rules" object initialized from FEN
93d1d7a7 37 drawOfferSent: false, //did I just ask for draw? (TODO: use for button style)
4b0384fa 38 people: [ ], //potential observers (TODO)
a6088c90
BA
39 };
40 },
41 watch: {
f7121527 42 '$route' (to, from) {
4fe5664d
BA
43 if (!!to.params["id"])
44 {
45 this.gameRef.id = to.params["id"];
46 this.gameRef.rid = to.query["rid"];
47 this.loadGame();
48 }
a6088c90
BA
49 },
50 },
a6088c90 51 created: function() {
f7121527 52 if (!!this.$route.params["id"])
a6088c90 53 {
f7121527
BA
54 this.gameRef.id = this.$route.params["id"];
55 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 56 this.loadGame();
f7121527 57 }
f7121527
BA
58 // TODO: how to know who is observing ? Send message to everyone with game ID ?
59 // and then just listen to (dis)connect events
3b450453
BA
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)
3b450453
BA
65 // --> doivent être enregistrés comme observers au niveau du serveur...
66 // non: poll users + events startObserving / stopObserving
b4fb1612 67 // (à faire au niveau du routeur ?)
3b450453 68
a6088c90
BA
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 {
f7121527
BA
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
c4f91d3f
BA
80 // NOTE: next call will trigger processMove()
81 this.$refs["basegame"].play(data.move,
82 "receive", this.game.vname!="Dark" ? "animate" : null);
a6088c90
BA
83 break;
84 case "pong": //received if we sent a ping (game still alive on our side)
85 if (this.gameRef.id != data.gameId)
f7121527 86 break; //games IDs don't match: the game is definitely over...
a6088c90
BA
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 => {
4b0384fa 91 this.st.conn.send(JSON.stringify({
a6088c90
BA
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;
f7121527 100 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves
93d1d7a7 101 // TODO: need to send along clock state (my current time) with my last move
a6088c90
BA
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)
4b0384fa 110 this.st.conn.send(JSON.stringify({
a6088c90
BA
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
4b0384fa 122 this.st.conn.send(JSON.stringify({
a6088c90
BA
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
c4f91d3f 131 this.play(data.lastMove, "animate"); //TODO: wrong call (3 args)
a6088c90 132 break;
93d1d7a7
BA
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");
a6088c90 140 break;
93d1d7a7
BA
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
a6088c90
BA
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 = () => {
4b0384fa
BA
168 this.st.conn.addEventListener('message', socketMessageListener);
169 this.st.conn.addEventListener('close', socketCloseListener);
a6088c90 170 };
4b0384fa
BA
171 this.st.conn.onmessage = socketMessageListener;
172 this.st.conn.onclose = socketCloseListener;
a6088c90
BA
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 {
4b0384fa 192 this.st.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
a6088c90
BA
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;
93d1d7a7
BA
209
210// Abort possible à tout moment avec message
211// Sorry I have to go / Game seems over / Game is not interesting
212
a6088c90
BA
213 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
214 //send message: "gameOver" avec score "?"
4b0384fa 215 // ==> BaseGame must listen to game.score change, and call "endgame(score)" in this case
a6088c90
BA
216 },
217 resign: function(e) {
218 if (!confirm("Resign the game?"))
219 return;
93d1d7a7
BA
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 }));
a6088c90 227 }
93d1d7a7
BA
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");
a6088c90 231 },
b196f8ea
BA
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)
6dd02928
BA
237 loadGame: function() {
238 GameStorage.get(this.gameRef, async (game) => {
4b0384fa
BA
239 this.game = Object.assign({},
240 game,
241 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
b4fb1612
BA
242 {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
243 p => p.sid == this.st.user.sid)]},
4b0384fa 244 );
6dd02928 245 const vModule = await import("@/variants/" + game.vname + ".js");
d6c1bf37 246 window.V = vModule.VariantRules;
6dd02928 247 this.vr = new V(game.fen);
6274a545
BA
248 // Post-processing: decorate each move with current FEN:
249 // (to be able to jump to any position quickly)
250 game.moves.forEach(move => {
c4f91d3f
BA
251 // NOTE: this is doing manually what BaseGame.play() achieve...
252 // but in a lighter "fast-forward" way
9d54ab89 253 move.color = this.vr.turn;
8a7452b5 254 this.vr.play(move);
9d54ab89 255 move.fen = this.vr.getFen();
6274a545
BA
256 });
257 this.vr.re_init(game.fen);
d6c1bf37 258 });
4fe5664d
BA
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// }
a6088c90 268 },
b4fb1612 269 // TODO: refactor this old "oppConnected" logic
6ec161b9
BA
270// oppConnected: function(uid) {
271// return this.opponents.some(o => o.id == uid && o.online);
272// },
9d54ab89 273 // Post-process a move (which was just played)
ce87ac6a 274 processMove: function(move) {
b4fb1612
BA
275 if (!this.game.mycolor)
276 return; //I'm just an observer
9d54ab89 277 // Update storage (corr or live)
c4f91d3f 278 const colorIdx = ["w","b","g","r"].indexOf(move.color);
9d54ab89
BA
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) => {
8a7452b5 284 obj[key] = move[key];
9d54ab89
BA
285 return obj;
286 }, {});
b4fb1612 287 // Send move ("newmove" event) to opponent(s) (if ours)
9d54ab89 288 // (otherwise move.elapsed is supposed to be already transmitted)
c4f91d3f 289 let addTime = undefined;
9d54ab89 290 if (move.color == this.game.mycolor)
b4fb1612 291 {
9d54ab89 292 const elapsed = Date.now() - GameStorage.getInitime();
b4fb1612
BA
293 this.game.players.forEach(p => {
294 if (p.sid != this.st.user.sid)
93d1d7a7 295 {
8a7452b5
BA
296 this.st.conn.send(JSON.stringify({
297 code: "newmove",
9d54ab89
BA
298 target: p.sid,
299 move: Object.assign({}, filtered_move, {elapsed: elapsed}),
8a7452b5 300 }));
93d1d7a7 301 }
b4fb1612 302 });
9d54ab89 303 move.elapsed = elapsed;
c4f91d3f
BA
304 // elapsed time is measured in milliseconds
305 addTime = this.game.increment - elapsed/1000;
b4fb1612 306 }
9d54ab89
BA
307 GameStorage.update({
308 colorIdx: colorIdx,
309 move: filtered_move,
310 fen: move.fen,
c4f91d3f
BA
311 addTime: addTime,
312 initime: (this.vr.turn == this.game.mycolor), //my turn now?
9d54ab89 313 });
b4fb1612 314 },
93d1d7a7 315 // TODO: this update function should also work for corr games
b4fb1612 316 gameOver: function(score) {
93d1d7a7 317 this.game.mode = "analyze";
9d54ab89
BA
318 GameStorage.update({
319 score: score,
320 });
ce87ac6a 321 },
a6088c90
BA
322 },
323};
324</script>