Some fixes. TODO: game.mode must be analyze when score is not '*' ==> simplify Board...
[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")
d4036efe 14 .button-group(v-if="game.mode!='analyze' && game.score=='*'")
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);
d4036efe 222 return;
b988c726 223 //const message = event.
d4036efe
BA
224 // Next line will trigger a "gameover" event, bubbling up till here
225 this.$refs["basegame"].endGame("?");
b988c726
BA
226 this.game.players.forEach(p => {
227 if (!!p.sid && p.sid != this.st.user.sid)
228 {
229 this.st.conn.send(JSON.stringify({
230 code: "abort",
231 msg: message,
232 target: p.sid,
233 }));
234 }
235 });
236 }
a6088c90
BA
237 },
238 resign: function(e) {
239 if (!confirm("Resign the game?"))
240 return;
93d1d7a7
BA
241 this.game.players.forEach(p => {
242 if (!!p.sid && p.sid != this.st.user.sid)
243 {
244 this.st.conn.send(JSON.stringify({
245 code: "resign",
246 target: p.sid,
247 }));
a6088c90 248 }
93d1d7a7
BA
249 });
250 // Next line will trigger a "gameover" event, bubbling up till here
251 this.$refs["basegame"].endGame(this.game.mycolor=="w" ? "0-1" : "1-0");
a6088c90 252 },
b196f8ea
BA
253 // 4 cases for loading a game:
254 // - from localStorage (one running game I play)
255 // - from indexedDB (one completed live game)
256 // - from server (one correspondance game I play[ed] or not)
257 // - from remote peer (one live game I don't play, finished or not)
6dd02928
BA
258 loadGame: function() {
259 GameStorage.get(this.gameRef, async (game) => {
d4036efe
BA
260 const vModule = await import("@/variants/" + game.vname + ".js");
261 window.V = vModule.VariantRules;
262 this.vr = new V(game.fenStart);
4b0384fa
BA
263 this.game = Object.assign({},
264 game,
265 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
b4fb1612
BA
266 {mycolor: [undefined,"w","b"][1 + game.players.findIndex(
267 p => p.sid == this.st.user.sid)]},
4b0384fa 268 );
d6c1bf37 269 });
4fe5664d
BA
270// // Poll all players except me (if I'm playing) to know online status.
271// // --> Send ping to server (answer pong if players[s] are connected)
272// if (this.gameInfo.players.some(p => p.sid == this.st.user.sid))
273// {
274// this.game.players.forEach(p => {
275// if (p.sid != this.st.user.sid)
276// this.st.conn.send(JSON.stringify({code:"ping", oppid:p.sid}));
277// });
278// }
a6088c90 279 },
b4fb1612 280 // TODO: refactor this old "oppConnected" logic
6ec161b9
BA
281// oppConnected: function(uid) {
282// return this.opponents.some(o => o.id == uid && o.online);
283// },
9d54ab89 284 // Post-process a move (which was just played)
ce87ac6a 285 processMove: function(move) {
b4fb1612
BA
286 if (!this.game.mycolor)
287 return; //I'm just an observer
9d54ab89 288 // Update storage (corr or live)
c4f91d3f 289 const colorIdx = ["w","b","g","r"].indexOf(move.color);
9d54ab89
BA
290 // https://stackoverflow.com/a/38750895
291 const allowed_fields = ["appear", "vanish", "start", "end"];
292 const filtered_move = Object.keys(move)
293 .filter(key => allowed_fields.includes(key))
294 .reduce((obj, key) => {
8a7452b5 295 obj[key] = move[key];
9d54ab89
BA
296 return obj;
297 }, {});
b4fb1612 298 // Send move ("newmove" event) to opponent(s) (if ours)
9d54ab89 299 // (otherwise move.elapsed is supposed to be already transmitted)
c4f91d3f 300 let addTime = undefined;
9d54ab89 301 if (move.color == this.game.mycolor)
b4fb1612 302 {
9d54ab89 303 const elapsed = Date.now() - GameStorage.getInitime();
b4fb1612
BA
304 this.game.players.forEach(p => {
305 if (p.sid != this.st.user.sid)
93d1d7a7 306 {
8a7452b5
BA
307 this.st.conn.send(JSON.stringify({
308 code: "newmove",
9d54ab89
BA
309 target: p.sid,
310 move: Object.assign({}, filtered_move, {elapsed: elapsed}),
8a7452b5 311 }));
93d1d7a7 312 }
b4fb1612 313 });
9d54ab89 314 move.elapsed = elapsed;
c4f91d3f
BA
315 // elapsed time is measured in milliseconds
316 addTime = this.game.increment - elapsed/1000;
b4fb1612 317 }
9d54ab89
BA
318 GameStorage.update({
319 colorIdx: colorIdx,
320 move: filtered_move,
321 fen: move.fen,
c4f91d3f
BA
322 addTime: addTime,
323 initime: (this.vr.turn == this.game.mycolor), //my turn now?
9d54ab89 324 });
b4fb1612 325 },
93d1d7a7 326 // TODO: this update function should also work for corr games
b4fb1612 327 gameOver: function(score) {
93d1d7a7 328 this.game.mode = "analyze";
9d54ab89
BA
329 GameStorage.update({
330 score: score,
331 });
ce87ac6a 332 },
a6088c90
BA
333 },
334};
335</script>