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