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==game.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: { //given in URL (rid = remote ID)
49 game: { }, //passed to BaseGame
50 vr: null, //"variant rules" object initialized from FEN
51 drawOfferSent: false, //did I just ask for draw? (TODO: draw variables?)
52 people: [ ], //potential observers (TODO)
57 if (!!to.params["id"])
59 this.gameRef.id = to.params["id"];
60 this.gameRef.rid = to.query["rid"];
66 if (!!this.$route.params["id"])
68 this.gameRef.id = this.$route.params["id"];
69 this.gameRef.rid = this.$route.query["rid"];
72 // TODO: how to know who is observing ? Send message to everyone with game ID ?
73 // and then just listen to (dis)connect events
76 // server always send "connect on " + URL ; then add to observers if game...
77 // detect multiple tabs connected (when connect ask server if my SID is already in use)
78 // router when access a game page tell to server I joined + game ID (no need rid)
79 // and ask server for current joined (= observers)
80 // when send to chat (or a move), reach only this group (send gid along)
82 // --> doivent être enregistrés comme observers au niveau du serveur...
83 // non: poll users + events startObserving / stopObserving
86 // TODO: also handle "draw accepted" (use opponents array?)
87 // --> must give this info also when sending lastState...
88 // and, if all players agree then OK draw (end game ...etc)
89 const socketMessageListener = msg => {
90 const data = JSON.parse(msg.data);
95 // TODO: observer on dark games must see all board ? Or alternate ? (seems better)
96 // ...or just see nothing as on buho21
97 this.$refs["basegame"].play(
98 data.move, this.game.vname!="Dark" ? "animate" : null);
100 case "pong": //received if we sent a ping (game still alive on our side)
101 if (this.gameRef.id != data.gameId)
102 break; //games IDs don't match: the game is definitely over...
103 this.oppConnected = true;
104 // Send our "last state" informations to opponent(s)
105 L = this.vr.moves.length;
106 Object.keys(this.opponents).forEach(oid => {
107 this.st.conn.send(JSON.stringify({
110 gameId: this.gameRef.id,
111 lastMove: (L>0?this.vr.moves[L-1]:undefined),
116 // TODO: refactor this, because at 3 or 4 players we may have missed 2 or 3 moves
117 case "lastate": //got opponent infos about last move
118 L = this.vr.moves.length;
119 if (this.gameRef.id != data.gameId)
120 break; //games IDs don't match: nothing we can do...
121 // OK, opponent still in game (which might be over)
122 if (this.score != "*")
124 // We finished the game (any result possible)
125 this.st.conn.send(JSON.stringify({
128 gameId: this.gameRef.id,
132 else if (!!data.score) //opponent finished the game
133 this.endGame(data.score);
134 else if (data.movesCount < L)
136 // We must tell last move to opponent
137 this.st.conn.send(JSON.stringify({
139 oppid: this.opponent.id,
140 gameId: this.gameRef.id,
141 lastMove: this.vr.moves[L-1],
145 else if (data.movesCount > L) //just got last move from him
146 this.play(data.lastMove, "animate");
148 case "resign": //..you won!
149 this.endGame(this.game.mycolor=="w"?"1-0":"0-1");
151 // TODO: also use (dis)connect info to count online players?
153 case "gamedisconnect":
154 if (this.mode=="human")
156 const online = (data.code == "connect");
157 // If this is an opponent ?
158 if (!!this.opponents[data.id])
159 this.opponents[data.id].online = online;
164 delete this.people[data.id];
166 this.people[data.id] = data.name;
172 const socketCloseListener = () => {
173 this.st.conn.addEventListener('message', socketMessageListener);
174 this.st.conn.addEventListener('close', socketCloseListener);
176 this.st.conn.onmessage = socketMessageListener;
177 this.st.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.st.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 "?"
216 // ==> BaseGame must listen to game.score change, and call "endgame(score)" in this case
218 resign: function(e) {
219 if (!confirm("Resign the game?"))
221 if (this.mode == "human" && this.oppConnected(this.oppid))
224 this.st.conn.send(JSON.stringify({code: "resign", oppid: this.oppid}));
225 } catch (INVALID_STATE_ERR) {
229 this.endGame(this.mycolor=="w"?"0-1":"1-0");
231 // 4 cases for loading a game:
232 // - from localStorage (one running game I play)
233 // - from indexedDB (one completed live game)
234 // - from server (one correspondance game I play[ed] or not)
235 // - from remote peer (one live game I don't play, finished or not)
236 loadGame: function() {
237 GameStorage.get(this.gameRef, async (game) => {
238 this.game = Object.assign({},
240 // NOTE: assign mycolor here, since BaseGame could also bs VS computer
241 {mycolor: ["w","b"][game.players.findIndex(p => p.sid == this.st.user.sid)]},
243 const vModule = await import("@/variants/" + game.vname + ".js");
244 window.V = vModule.VariantRules;
245 this.vr = new V(game.fen);
247 // // Poll all players except me (if I'm playing) to know online status.
248 // // --> Send ping to server (answer pong if players[s] are connected)
249 // if (this.gameInfo.players.some(p => p.sid == this.st.user.sid))
251 // this.game.players.forEach(p => {
252 // if (p.sid != this.st.user.sid)
253 // this.st.conn.send(JSON.stringify({code:"ping", oppid:p.sid}));
257 oppConnected: function(uid) {
258 return this.opponents.some(o => o.id == uid && o.online);
260 processMove: function(move) {
261 // TODO: process some opponent's move