Finished Hall.js for now - TODO: live + corr games
[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")
6fba6e0c 14 // TODO: also show players names
809ba2aa 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
9aa229f3
BA
27// ==> après, implémenter/vérifier les passages de challenges + parties en cours
28// observer,
29// + problèmes, habiller et publier. (+ corr...)
6fba6e0c
BA
30 // TODO: how to know who is observing ? Send message to everyone with game ID ?
31 // and then just listen to (dis)connect events
32 // server always send "connect on " + URL ; then add to observers if game...
33// router when access a game page tell to server I joined + game ID (no need rid)
34// and ask server for current joined (= observers)
35// when send to chat (or a move), reach only this group (send gid along)
36// -> doivent être enregistrés comme observers au niveau du serveur...
37 // non: poll users + events startObserving / stopObserving
38 // (à faire au niveau du routeur ?)
9aa229f3
BA
39-->
40
a6088c90 41<script>
46284a2f 42import BaseGame from "@/components/BaseGame.vue";
a6088c90
BA
43//import Chat from "@/components/Chat.vue";
44//import MoveList from "@/components/MoveList.vue";
45import { store } from "@/store";
967a2686 46import { GameStorage } from "@/utils/gameStorage";
5b87454c 47import { ppt } from "@/utils/datetime";
a6088c90
BA
48
49export default {
50 name: 'my-game',
51 components: {
52 BaseGame,
53 },
f7121527 54 // gameRef: to find the game in (potentially remote) storage
a6088c90
BA
55 data: function() {
56 return {
57 st: store.state,
4b0384fa
BA
58 gameRef: { //given in URL (rid = remote ID)
59 id: "",
60 rid: ""
61 },
62 game: { }, //passed to BaseGame
6fba6e0c
BA
63 oppConnected: false,
64 corrMsg: "", //to send offline messages in corr games
809ba2aa 65 virtualClocks: [0, 0], //initialized with true game.clocks
6dd02928 66 vr: null, //"variant rules" object initialized from FEN
6fba6e0c 67 drawOffer: "", //TODO: use for button style
4b0384fa 68 people: [ ], //potential observers (TODO)
a6088c90
BA
69 };
70 },
71 watch: {
f7121527 72 '$route' (to, from) {
4fe5664d
BA
73 if (!!to.params["id"])
74 {
75 this.gameRef.id = to.params["id"];
76 this.gameRef.rid = to.query["rid"];
77 this.loadGame();
78 }
a6088c90 79 },
5b87454c 80 "game.clocks": function(newState) {
809ba2aa
BA
81 this.virtualClocks = newState.map(s => ppt(s));
82 const currentTurn = this.vr.turn;
6fba6e0c 83 const colorIdx = ["w","b"].indexOf(currentTurn);
809ba2aa
BA
84 let countdown = newState[colorIdx] -
85 (Date.now() - this.game.initime[colorIdx])/1000;
86 const myTurn = (currentTurn == this.game.mycolor);
809ba2aa 87 let clockUpdate = setInterval(() => {
809ba2aa
BA
88 if (countdown <= 0 || this.vr.turn != currentTurn)
89 {
90 clearInterval(clockUpdate);
91 if (countdown <= 0 && myTurn)
92 {
93 this.$refs["basegame"].endGame(
94 this.game.mycolor=="w" ? "0-1" : "1-0", "Time");
6fba6e0c
BA
95 this.st.conn.send(JSON.stringify({
96 code: "timeover",
97 target: this.game.oppid,
98 }));
809ba2aa
BA
99 }
100 }
9aa229f3
BA
101 else
102 {
103 // TODO: with Vue 3, just do this.virtualClocks[colorIdx] = ppt(--countdown)
104 this.$set(this.virtualClocks, colorIdx, ppt(Math.max(0, --countdown)));
105 }
809ba2aa 106 }, 1000);
5b87454c 107 },
a6088c90 108 },
a6088c90 109 created: function() {
f7121527 110 if (!!this.$route.params["id"])
a6088c90 111 {
f7121527
BA
112 this.gameRef.id = this.$route.params["id"];
113 this.gameRef.rid = this.$route.query["rid"];
b196f8ea 114 this.loadGame();
f7121527 115 }
cdb34c93
BA
116 // TODO: onopen, ask lastState informations + update observers and players status
117 const socketCloseListener = () => {
118 store.socketCloseListener(); //reinitialize connexion (in store.js)
a9b131f1 119 this.st.conn.addEventListener('message', this.socketMessageListener);
cdb34c93
BA
120 this.st.conn.addEventListener('close', socketCloseListener);
121 };
122 this.st.conn.onmessage = this.socketMessageListener;
123 this.st.conn.onclose = socketCloseListener;
124 },
125 methods: {
126 socketMessageListener: function(msg) {
a6088c90 127 const data = JSON.parse(msg.data);
a6088c90
BA
128 switch (data.code)
129 {
f7121527 130 case "newmove":
c4f91d3f
BA
131 // NOTE: next call will trigger processMove()
132 this.$refs["basegame"].play(data.move,
133 "receive", this.game.vname!="Dark" ? "animate" : null);
a6088c90
BA
134 break;
135 case "pong": //received if we sent a ping (game still alive on our side)
6fba6e0c 136 {
a6088c90
BA
137 this.oppConnected = true;
138 // Send our "last state" informations to opponent(s)
6fba6e0c
BA
139 const L = this.game.moves.length;
140 this.st.conn.send(JSON.stringify({
141 code: "lastate",
142 target: this.game.oppid,
143 gameId: this.gameRef.id,
144 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
145 score: this.game.score,
146 movesCount: L,
147 drawOffer: this.drawOffer,
148 clocks: this.game.clocks,
149 }));
a6088c90 150 break;
6fba6e0c 151 }
a6088c90 152 case "lastate": //got opponent infos about last move
6fba6e0c
BA
153 {
154 const L = this.game.moves.length;
a6088c90
BA
155 if (this.gameRef.id != data.gameId)
156 break; //games IDs don't match: nothing we can do...
157 // OK, opponent still in game (which might be over)
6fba6e0c 158 if (data.movesCount > L)
a6088c90 159 {
6fba6e0c
BA
160 // Just got last move from him
161 this.$refs["basegame"].play(data.lastMove, "receive");
162 if (data.score != "*" && this.game.score == "*")
163 {
164 // Opponent resigned or aborted game, or accepted draw offer
165 // (this is not a stalemate or checkmate)
166 this.$refs["basegame"].endGame(data.score, "Opponent action");
167 }
168 this.game.clocks = data.clocks;
169 this.drawOffer = data.drawOffer;
a6088c90 170 }
a6088c90
BA
171 else if (data.movesCount < L)
172 {
173 // We must tell last move to opponent
4b0384fa 174 this.st.conn.send(JSON.stringify({
a6088c90 175 code: "lastate",
6fba6e0c 176 target: this.game.oppid,
a6088c90 177 gameId: this.gameRef.id,
6fba6e0c
BA
178 lastMove: (L>0 ? this.game.moves[L-1] : undefined),
179 score: this.game.score,
a6088c90 180 movesCount: L,
6fba6e0c
BA
181 drawOffer: this.drawOffer,
182 clocks: this.game.clocks,
a6088c90
BA
183 }));
184 }
a6088c90 185 break;
6fba6e0c 186 }
93d1d7a7
BA
187 case "resign":
188 this.$refs["basegame"].endGame(
189 this.game.mycolor=="w" ? "1-0" : "0-1", "Resign");
190 break;
191 case "timeover":
192 this.$refs["basegame"].endGame(
193 this.game.mycolor=="w" ? "1-0" : "0-1", "Time");
a6088c90 194 break;
93d1d7a7
BA
195 case "abort":
196 this.$refs["basegame"].endGame("?", "Abort: " + data.msg);
197 break;
2cc10cdb
BA
198 case "draw":
199 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
200 break;
201 case "drawoffer":
202 this.drawOffer = "received";
203 break;
7e1a1fe9
BA
204 case "askfullgame":
205 // TODO: just give game; observers are listed here anyway:
206 // gameconnect?
207 break;
93d1d7a7
BA
208 // TODO: drawaccepted (click draw button before sending move ==> draw offer in move)
209 // ==> on "newmove", check "drawOffer" field
a6088c90
BA
210 // TODO: also use (dis)connect info to count online players?
211 case "gameconnect":
212 case "gamedisconnect":
6fba6e0c
BA
213 const online = (data.code == "gameconnect");
214 // If this is an opponent ?
215 if (this.game.oppid == data.id)
216 this.oppConnected = true;
217 else
a6088c90 218 {
6fba6e0c
BA
219 // Or an observer ?
220 if (!online)
221 delete this.people[data.id];
a6088c90 222 else
6fba6e0c 223 this.people[data.id] = data.name;
a6088c90
BA
224 }
225 break;
226 }
cdb34c93 227 },
a6088c90 228 offerDraw: function() {
2cc10cdb 229 // TODO: also for corr games
6fba6e0c
BA
230 if (this.drawOffer == "received")
231 {
2cc10cdb 232 if (!confirm("Accept draw?"))
6fba6e0c
BA
233 return;
234 this.st.conn.send(JSON.stringify({code:"draw", target:this.game.oppid}));
2cc10cdb
BA
235 this.$refs["basegame"].endGame("1/2", "Mutual agreement");
236 }
6fba6e0c
BA
237 else if (this.drawOffer == "sent")
238 this.drawOffer = "";
239 else
240 {
241 if (!confirm("Offer draw?"))
242 return;
2cc10cdb 243 this.st.conn.send(JSON.stringify({code:"drawoffer", target:this.game.oppid}));
a6088c90
BA
244 }
245 },
246 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
247 receiveDrawOffer: function() {
248 //if (...)
249 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
250 // if accept: send message "draw"
251 },
b988c726 252 abortGame: function(event) {
9aa229f3 253 let modalBox = document.getElementById("modalAbort");
b988c726
BA
254 if (!event)
255 {
256 // First call show options:
b988c726
BA
257 modalBox.checked = true;
258 }
259 else
260 {
9aa229f3
BA
261 modalBox.checked = false; //decision made: box disappear
262 const message = event.target.innerText;
d4036efe 263 // Next line will trigger a "gameover" event, bubbling up till here
9aa229f3 264 this.$refs["basegame"].endGame("?", "Abort: " + message);
6fba6e0c
BA
265 this.st.conn.send(JSON.stringify({
266 code: "abort",
267 msg: message,
268 target: this.game.oppid,
269 }));
b988c726 270 }
a6088c90
BA
271 },
272 resign: function(e) {
273 if (!confirm("Resign the game?"))
274 return;
6fba6e0c
BA
275 this.st.conn.send(JSON.stringify({
276 code: "resign",
277 target: this.game.oppid,
278 }));
93d1d7a7 279 // Next line will trigger a "gameover" event, bubbling up till here
809ba2aa
BA
280 this.$refs["basegame"].endGame(
281 this.game.mycolor=="w" ? "0-1" : "1-0", "Resign");
a6088c90 282 },
967a2686
BA
283 // 3 cases for loading a game:
284 // - from indexedDB (running or completed live game I play)
b196f8ea
BA
285 // - from server (one correspondance game I play[ed] or not)
286 // - from remote peer (one live game I don't play, finished or not)
967a2686
BA
287 loadGame: function(game) {
288 const afterRetrieval = async (game) => {
a9b131f1
BA
289 const vname = this.st.variants.filter(v => v.id == game.vid)[0].name;
290 const vModule = await import("@/variants/" + vname + ".js");
d4036efe 291 window.V = vModule.VariantRules;
809ba2aa 292 this.vr = new V(game.fen);
6fba6e0c 293 const myIdx = game.players.findIndex(p => p.sid == this.st.user.sid);
4b0384fa
BA
294 this.game = Object.assign({},
295 game,
296 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
6fba6e0c 297 {
a9b131f1 298 vname: vname,
6fba6e0c
BA
299 mycolor: [undefined,"w","b"][myIdx+1],
300 // opponent sid not strictly required, but easier
301 oppid: (myIdx < 0 ? undefined : game.players[1-myIdx].sid),
302 }
4b0384fa 303 );
6fba6e0c
BA
304 if (!!this.game.oppid)
305 {
306 // Send ping to server (answer pong if players[s] are connected)
a36a09c0 307 this.st.conn.send(JSON.stringify({code:"ping", target:this.game.oppid}));
6fba6e0c 308 }
967a2686
BA
309 };
310 if (!!game)
311 return afterRetrival(game);
312 if (!!this.gameRef.rid)
313 {
7e1a1fe9 314 this.st.conn.send(JSON.stringify({code:"askfullgame", target:this.gameRef.rid}));
967a2686
BA
315 // TODO: just send a game request message to the remote player,
316 // and when receiving answer just call loadGame(received_game)
317 // + remote peer should have registered us as an observer
318 // (send moves updates + resign/abort/draw actions)
967a2686
BA
319 }
320 else
321 {
322 GameStorage.get(this.gameRef.id, async (game) => {
323 afterRetrieval(game);
324 });
325 }
a6088c90 326 },
9d54ab89 327 // Post-process a move (which was just played)
ce87ac6a 328 processMove: function(move) {
b4fb1612
BA
329 if (!this.game.mycolor)
330 return; //I'm just an observer
9d54ab89 331 // Update storage (corr or live)
6fba6e0c 332 const colorIdx = ["w","b"].indexOf(move.color);
9d54ab89
BA
333 // https://stackoverflow.com/a/38750895
334 const allowed_fields = ["appear", "vanish", "start", "end"];
335 const filtered_move = Object.keys(move)
336 .filter(key => allowed_fields.includes(key))
337 .reduce((obj, key) => {
8a7452b5 338 obj[key] = move[key];
9d54ab89
BA
339 return obj;
340 }, {});
b4fb1612 341 // Send move ("newmove" event) to opponent(s) (if ours)
c4f91d3f 342 let addTime = undefined;
9d54ab89 343 if (move.color == this.game.mycolor)
b4fb1612 344 {
809ba2aa 345 const elapsed = Date.now() - this.game.initime[colorIdx];
5b87454c
BA
346 // elapsed time is measured in milliseconds
347 addTime = this.game.increment - elapsed/1000;
6fba6e0c
BA
348 this.st.conn.send(JSON.stringify({
349 code: "newmove",
350 target: this.game.oppid,
351 move: Object.assign({}, filtered_move, {addTime: addTime}),
352 }));
b4fb1612 353 }
5b87454c
BA
354 else
355 addTime = move.addTime; //supposed transmitted
6fba6e0c 356 const nextIdx = ["w","b"].indexOf(this.vr.turn);
967a2686
BA
357 GameStorage.update(this.gameRef.id,
358 {
9d54ab89 359 colorIdx: colorIdx,
809ba2aa 360 nextIdx: nextIdx,
9d54ab89
BA
361 move: filtered_move,
362 fen: move.fen,
c4f91d3f 363 addTime: addTime,
9d54ab89 364 });
967a2686
BA
365 // Also update current game object:
366 this.game.moves.push(move);
367 this.game.fen = move.fen;
27d18a24
BA
368 //TODO: just this.game.clocks[colorIdx] += (!!addTime ? addTime : 0);
369 this.$set(this.game.clocks, colorIdx,
370 this.game.clocks[colorIdx] + (!!addTime ? addTime : 0));
809ba2aa 371 this.game.initime[nextIdx] = Date.now();
b4fb1612 372 },
93d1d7a7 373 // TODO: this update function should also work for corr games
b4fb1612 374 gameOver: function(score) {
93d1d7a7 375 this.game.mode = "analyze";
5b87454c
BA
376 GameStorage.update(this.gameRef.id,
377 {
9d54ab89
BA
378 score: score,
379 });
ce87ac6a 380 },
a6088c90
BA
381 },
382};
383</script>
7e1a1fe9
BA
384
385<style lang="sass">
386// TODO
387</style>