1 <!-- TODO: component Game, + handle players + observers connect/disconnect
2 event = "gameconnect" ...etc
3 connect/disconnect with sid+name (ID not required); name slightly redundant but easier
4 quand on arrive dans la partie, on poll les sids pour savoir qui est en ligne (ping)
5 (éventuel échange lastate avec les connectés, pong ...etc)
6 ensuite quand qqun se deco il suffit d'écouter "disconnect"
7 pareil quand quelqu'un reco.
8 (c'est assez rudimentaire et écoute trop de messages, mais dans un premier temps...)
9 // TODO: [in game] send move + elapsed time (in milliseconds); in case of "lastate" message too
10 // TODO: if I'm an observer and player(s) disconnect/reconnect, how to find me ?
11 // onClick :: ask full game to remote player, and register as an observer in game
12 // (use gameId to communicate)
13 // on landing on game :: if gameId not found locally, check remotely
14 // ==> il manque un param dans game : "remoteId"
18 .col-sm-12.col-md-10.col-md-offset-1.col-lg-8.col-lg-offset-2
19 BaseGame(:game="game" :vr="vr" ref="basegame" @newmove="processMove")
20 .button-group(v-if="game.mode!='analyze'")
21 button(@click="offerDraw") Draw
22 button(@click="abortGame") Abort
23 button(@click="resign") Resign
24 div(v-if="game.mode=='corr'")
25 textarea(v-show="score=='*' && vr.turn==mycolor" v-model="corrMsg")
26 div(v-show="cursor>=0") {{ moves[cursor].message }}
30 import BaseGame from "@/components/BaseGame.vue";
31 //import Chat from "@/components/Chat.vue";
32 //import MoveList from "@/components/MoveList.vue";
33 import { store } from "@/store";
34 import { GameStorage } from "@/utils/storage";
41 // gameRef: to find the game in (potentially remote) storage
45 gameRef: {id: "", rid: ""}, //given in URL (rid = remote ID)
46 game: {}, //passed to BaseGame
47 vr: null, //"variant rules" object initialized from FEN
48 drawOfferSent: false, //did I just ask for draw? (TODO: draw variables?)
49 people: [], //potential observers (TODO)
54 if (!!to.params["id"])
56 this.gameRef.id = to.params["id"];
57 this.gameRef.rid = to.query["rid"];
63 if (!!this.$route.params["id"])
65 this.gameRef.id = this.$route.params["id"];
66 this.gameRef.rid = this.$route.query["rid"];
69 // TODO: how to know who is observing ? Send message to everyone with game ID ?
70 // and then just listen to (dis)connect events
73 // server always send "connect on " + URL ; then add to observers if game...
74 // detect multiple tabs connected (when connect ask server if my SID is already in use)
75 // router when access a game page tell to server I joined + game ID (no need rid)
76 // and ask server for current joined (= observers)
77 // when send to chat (or a move), reach only this group (send gid along)
79 // --> doivent être enregistrés comme observers au niveau du serveur...
80 // non: poll users + events startObserving / stopObserving
83 // TODO: also handle "draw accepted" (use opponents array?)
84 // --> must give this info also when sending lastState...
85 // and, if all players agree then OK draw (end game ...etc)
86 const socketMessageListener = msg => {
87 const data = JSON.parse(msg.data);
92 // TODO: observer on dark games must see all board ? Or alternate ? (seems better)
93 // ...or just see nothing as on buho21
94 this.$refs["basegame"].play(
95 data.move, this.game.vname!="Dark" ? "animate" : null);
97 case "pong": //received if we sent a ping (game still alive on our side)
98 if (this.gameRef.id != data.gameId)
99 break; //games IDs don't match: the game is definitely over...
100 this.oppConnected = true;
101 // Send our "last state" informations to opponent(s)
102 L = this.vr.moves.length;
103 Object.keys(this.opponents).forEach(oid => {
104 this.conn.send(JSON.stringify({
107 gameId: this.gameRef.id,
108 lastMove: (L>0?this.vr.moves[L-1]:undefined),
113 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves
114 case "lastate": //got opponent infos about last move
115 L = this.vr.moves.length;
116 if (this.gameRef.id != data.gameId)
117 break; //games IDs don't match: nothing we can do...
118 // OK, opponent still in game (which might be over)
119 if (this.score != "*")
121 // We finished the game (any result possible)
122 this.conn.send(JSON.stringify({
125 gameId: this.gameRef.id,
129 else if (!!data.score) //opponent finished the game
130 this.endGame(data.score);
131 else if (data.movesCount < L)
133 // We must tell last move to opponent
134 this.conn.send(JSON.stringify({
136 oppid: this.opponent.id,
137 gameId: this.gameRef.id,
138 lastMove: this.vr.moves[L-1],
142 else if (data.movesCount > L) //just got last move from him
143 this.play(data.lastMove, "animate");
145 case "resign": //..you won!
146 this.endGame(this.mycolor=="w"?"1-0":"0-1");
148 // TODO: also use (dis)connect info to count online players?
150 case "gamedisconnect":
151 if (this.mode=="human")
153 const online = (data.code == "connect");
154 // If this is an opponent ?
155 if (!!this.opponents[data.id])
156 this.opponents[data.id].online = online;
161 delete this.people[data.id];
163 this.people[data.id] = data.name;
169 const socketCloseListener = () => {
170 this.conn.addEventListener('message', socketMessageListener);
171 this.conn.addEventListener('close', socketCloseListener);
175 this.conn.onmessage = socketMessageListener;
176 this.conn.onclose = socketCloseListener;
179 // dans variant.js (plutôt room.js) conn gère aussi les challenges
180 // et les chats dans chat.js. Puis en webRTC, repenser tout ça.
182 offerDraw: function() {
183 if (!confirm("Offer draw?"))
185 // Stay in "draw offer sent" state until next move is played
186 this.drawOfferSent = true;
187 if (this.subMode == "corr")
189 // TODO: set drawOffer on in game (how ?)
193 this.opponents.forEach(o => {
197 this.conn.send(JSON.stringify({code: "draw", oppid: o.id}));
198 } catch (INVALID_STATE_ERR) {
205 // + conn handling: "draw" message ==> agree for draw (if we have "drawOffered" at true)
206 receiveDrawOffer: function() {
208 // TODO: ignore if preventDrawOffer is set; otherwise show modal box with option "prevent future offers"
209 // if accept: send message "draw"
211 abortGame: function() {
212 if (!confirm("Abort the game?"))
214 //+ bouton "abort" avec score == "?" + demander confirmation pour toutes ces actions,
215 //send message: "gameOver" avec score "?"
217 resign: function(e) {
218 if (!confirm("Resign the game?"))
220 if (this.mode == "human" && this.oppConnected(this.oppid))
223 this.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
224 } catch (INVALID_STATE_ERR) {
228 this.endGame(this.mycolor=="w"?"0-1":"1-0");
230 // 4 cases for loading a game:
231 // - from localStorage (one running game I play)
232 // - from indexedDB (one completed live game)
233 // - from server (one correspondance game I play[ed] or not)
234 // - from remote peer (one live game I don't play, finished or not)
235 loadGame: function() {
236 GameStorage.get(this.gameRef, async (game) => {
238 const vModule = await import("@/variants/" + game.vname + ".js");
239 window.V = vModule.VariantRules;
240 this.vr = new V(game.fen);
242 // // Poll all players except me (if I'm playing) to know online status.
243 // // --> Send ping to server (answer pong if players[s] are connected)
244 // if (this.gameInfo.players.some(p => p.sid == this.st.user.sid))
246 // this.game.players.forEach(p => {
247 // if (p.sid != this.st.user.sid)
248 // this.st.conn.send(JSON.stringify({code:"ping", oppid:p.sid}));
252 oppConnected: function(uid) {
253 return this.opponents.some(o => o.id == uid && o.online);
255 processMove: function(move) {
256 // TODO: process some opponent's move