From: Benjamin Auder Date: Mon, 4 Mar 2019 15:18:27 +0000 (+0100) Subject: Save state X-Git-Url: https://git.auder.net/game/vendor/current/%7B%7B?a=commitdiff_plain;h=5bd05dba30fc83821637b6f3f080ca72da4bb157;p=vchess.git Save state --- diff --git a/client/src/views/Hall.vue b/client/src/views/Hall.vue index 16ce9bc7..f4ccc484 100644 --- a/client/src/views/Hall.vue +++ b/client/src/views/Hall.vue @@ -79,6 +79,7 @@ import { checkChallenge } from "@/data/challengeCheck"; import { ArrayFun } from "@/utils/array"; import { ajax } from "@/utils/ajax"; import { getRandString, shuffle } from "@/utils/alea"; +import { extractTime } from "@/utils/timeControl"; import GameList from "@/components/GameList.vue"; import ChallengeList from "@/components/ChallengeList.vue"; export default { @@ -176,10 +177,10 @@ export default { return NbPlayers[this.st.variants[idxInVariants].name].includes(nbp); }, showGame: function(game) { - // NOTE: if we are an observer, the game will be found in main games list - // (sent by connected remote players) - // TODO: game path ? /vname/gameId seems better - this.$router.push("/" + game.id); + // NOTE: we are an observer, since only games I don't play are shown here + // ==> Moves sent by connected remote player(s) + const sids = game.players.map(p => p.sid).join(","); + this.$router.push("/" + game.id + "?sids=" + sids); }, getVname: function(vid) { const vIdx = this.st.variants.findIndex(v => v.id == vid); @@ -189,6 +190,10 @@ export default { const pIdx = this.players.findIndex(pl => pl.name == pname); return (pIdx === -1 ? null : this.players[pIdx].sid); }, + getPname: function(sid) { + const pIdx = this.players.findIndex(pl => pl.sid == sid); + return (pIdx === -1 ? null : this.players[pIdx].name); + }, sendSomethingTo: function(to, code, obj, warnDisconnected) { const doSend = (code, obj, sid) => { this.st.conn.send(JSON.stringify(Object.assign( @@ -308,9 +313,10 @@ export default { // * If corr: notify "new game has started", give link, but do not redirect case "newgame": { - // TODO: new game just started: data contain all informations - // (id, players, time control, fenStart ...) - // + cid to remove challenge from list + // Delete corresponding challenge: + ArrayFun.remove(this.challenges, c => c.id == data.cid); + // New game just started: data contain all informations + this.newGame(data.gameInfo); break; } // * - receive "accept/withdraw/cancel challenge": apply action to challenges list @@ -318,7 +324,6 @@ export default { case "acceptchallenge": { // Someone accept an open (or targeted) challenge - // TODO: keep SIDs, since we need them to notify newgame after chall is complete const cIdx = this.challenges.findIndex(c => c.id == data.cid); let c = this.challenges[cIdx]; if (!c.seats) @@ -351,8 +356,8 @@ export default { } case "refusechallenge": { - // TODO: show "player XXX refused challenge", and - // remove challenge from list. + alert(this.getPname(data.from) + " refused your challenge"); + ArrayFun.remove(this.challenges, c => c.id == data.cid); break; } case "deletechallenge": @@ -360,15 +365,13 @@ export default { ArrayFun.remove(this.challenges, c => c.id == data.cid); break; } - // TODO: distinguish hallConnect and gameConnect? - // Or (better) global variable players + game variable: "observers" case "connect": -// * - receive "player connect": send our current challenge (to him or global) -// * Also send all our games (live - max 1 - and corr) [in web worker ?] { this.players.push({name:"", id:0, sid:data.sid}); this.st.conn.send(JSON.stringify({code:"askidentity", target:data.sid})); break; +// * - receive "player connect": TODO = send our current challenge (to him or global) +// * Also send all our games (live - max 1 - and corr) [in web worker ?] } // * - receive "player disconnect": remove from players list case "disconnect": @@ -490,6 +493,8 @@ export default { ArrayFun.remove(this.challenges, ch => ch.id == c.id); } }, + // c.type == corr alors use id...sinon sid (figés) + // NOTE: only for live games ? launchGame: function(c) { // Just assign colors and pass the message const vname = this.getVname(c.vid); @@ -497,33 +502,31 @@ export default { window.V = vModule.VariantRules; let players = [c.from]; Array.prototype.push.apply(players, c.seats); - c.type == corr alors use id...sinon sid (figés) let gameInfo = { - cid: c.id, //required to remove challenge fen: c.fen || V.GenRandInitFen(), // Shuffle players order (white then black then other colors). - // Players' names are not required - players: shuffle(players).map(p => {id:p.id, sid:p.sid}, + // Players' names may be required if game start when a player is offline + players: shuffle(players).map(p => {name:p.name, sid:p.sid}, vid: c.vid, timeControl: c.timeControl, }; c.seats.forEach(s => { + // NOTE: cid required to remove challenge this.st.conn.send(JSON.stringify({code:"newgame", - gameInfo:gameInfo, target:s.sid})); + gameInfo:gameInfo, cid:c.id, target:s.sid})); }); + // Delete corresponding challenge: + ArrayFun.remove(this.challenges, ch => ch.id == c.id); this.newGame(gameInfo); //also! }, + // NOTE: for live games only (corr games are laucnhed on server) newGame: function(gameInfo) { - // Extract times (in [milli?]seconds), set clocks, - // store in localStorage if live (on server otherwise) -// const fen = chall.fen || V.GenRandInitFen(); -// const game = {}; //TODO: fen, players, time ... -// //setStorage(game); //TODO -// game.players.forEach(p => { //...even if game is by corr (could be played live, why not...) -// this.conn.send( -// JSON.stringify({code:"newgame", oppid:p.id, game:game})); -// }); + // Extract times (in [milli]seconds), set clocks, store in localStorage + const tc = extractTime(gameInfo.timeControl); + dddddddd + // TODO: [in game] send move + elapsed time (in milliseconds); in case of "lastate" message too + // //setStorage(game); //TODO // if (this.settings.sound >= 1) // new Audio("/sounds/newgame.mp3").play().catch(err => {}); }, diff --git a/server/sockets.js b/server/sockets.js index a8e393e6..f3d1928d 100644 --- a/server/sockets.js +++ b/server/sockets.js @@ -3,52 +3,50 @@ const url = require('url'); // Node version in Ubuntu 16.04 does not know about URL class function getJsonFromUrl(url) { - const query = url.substr(2); //starts with "/?" - let result = {}; - query.split("&").forEach((part) => { - const item = part.split("="); - result[item[0]] = decodeURIComponent(item[1]); - }); - return result; + const query = url.substr(2); //starts with "/?" + let result = {}; + query.split("&").forEach((part) => { + const item = part.split("="); + result[item[0]] = decodeURIComponent(item[1]); + }); + return result; } // Removal in array of strings (socket IDs) function remInArray(arr, item) { - const idx = arr.indexOf(item); - if (idx >= 0) - arr.splice(idx, 1); + const idx = arr.indexOf(item); + if (idx >= 0) + arr.splice(idx, 1); } // TODO: empêcher multi-log du même user (envoyer le user ID + secret en même temps que name et...) // --> si secret ne matche pas celui trouvé en DB, stop -// TODO: this file "in the end" would be much simpler, essentially just tracking connect/disconnect -// (everything else using WebRTC) // TODO: lorsque challenge accepté, seul le dernier joueur à accepter envoi message "please start game" // avec les coordonnées des participants. Le serveur renvoit alors les détails de la partie (couleurs, position) //TODO: programmatic re-navigation on current game if we receive a move and are not there module.exports = function(wss) { - let clients = {}; //associative array sid --> socket - wss.on("connection", (socket, req) => { - const query = getJsonFromUrl(req.url); - const sid = query["sid"]; + let clients = {}; //associative array sid --> socket + wss.on("connection", (socket, req) => { + const query = getJsonFromUrl(req.url); + const sid = query["sid"]; // Ignore duplicate connections (on the same live game that we play): - if (!!clients[sid]) - return socket.send(JSON.stringify({code:"duplicate"})); - clients[sid] = socket; - // Notify room: + if (!!clients[sid]) + return socket.send(JSON.stringify({code:"duplicate"})); + clients[sid] = socket; + // Notify room: Object.keys(clients).forEach(k => { if (k != sid) clients[k].send(JSON.stringify({code:"connect",sid:sid})); }); socket.on("message", objtxt => { - let obj = JSON.parse(objtxt); + let obj = JSON.parse(objtxt); if (!!obj.target && !clients[obj.target]) return; //receiver not connected, nothing we can do //console.log(obj.code); - switch (obj.code) - { + switch (obj.code) + { case "pollclients": socket.send(JSON.stringify({code:"pollclients", sockIds:Object.keys(clients).filter(k => k != sid)})); @@ -70,7 +68,6 @@ module.exports = function(wss) { JSON.stringify({code:"identity",user:obj.user})); break; case "challenge": - // Relay challenge to other player clients[obj.target].send( JSON.stringify({code:"challenge", chall:obj.chall, from:sid})); break; @@ -82,45 +79,49 @@ module.exports = function(wss) { clients[obj.target].send( JSON.stringify({code:"withdrawchallenge", cid:obj.cid, from:sid})); break; + case "refusechallenge": + clients[obj.target].send( + JSON.stringify({code:"refusechallenge", cid:obj.cid, from:sid})); + break; case "newgame": clients[obj.target].send(JSON.stringify( - {code:"newgame", gameInfo:obj.gameInfo})); + {code:"newgame", gameInfo:obj.gameInfo, cid:obj.cid})); break; case "game": // TODO: relay (live) game to other player break; - case "newchat": + case "newchat": clients[obj.target].send(JSON.stringify({code:"newchat",msg:obj.msg})); - break; - // Transmit chats and moves to current room - // TODO: WebRTC instead in this case (most demanding?) - case "newmove": + break; + // Transmit chats and moves to current room + // TODO: WebRTC instead in this case (most demanding?) + case "newmove": clients[obj.target].send(JSON.stringify({code:"newmove",move:obj.move})); - break; - // TODO: generalize that for several opponents - case "ping": - socket.send(JSON.stringify({code:"pong",gameId:obj.gameId})); - break; - case "lastate": + break; + // TODO: generalize that for several opponents + case "ping": + socket.send(JSON.stringify({code:"pong",gameId:obj.gameId})); + break; + case "lastate": const oppId = obj.target; obj.oppid = sid; //I'm the opponent of my opponent(s) clients[oppId].send(JSON.stringify(obj)); - break; - // TODO: moreover, here, game info should be sent (through challenge; not stored here) - // TODO: also other challenge events - case "resign": + break; + // TODO: moreover, here, game info should be sent (through challenge; not stored here) + // TODO: also other challenge events + case "resign": clients[obj.target].send(JSON.stringify({code:"resign"})); - break; - // TODO: case "challenge" (get ID) --> send to all, "acceptchallenge" (with ID) --> send to all, "cancelchallenge" --> send to all - // also, "sendgame" (give current game info, if any) --> to new connections, "sendchallenges" (same for challenges) --> to new connections - } - }); - socket.on("close", () => { - delete clients[sid]; + break; + // TODO: case "challenge" (get ID) --> send to all, "acceptchallenge" (with ID) --> send to all, "cancelchallenge" --> send to all + // also, "sendgame" (give current game info, if any) --> to new connections, "sendchallenges" (same for challenges) --> to new connections + } + }); + socket.on("close", () => { + delete clients[sid]; // Notify every other connected client Object.keys(clients).forEach( k => { clients[k].send(JSON.stringify({code:"disconnect",sid:sid})); }); - }); - }); + }); + }); }