On create or join, now retrieves initial game state form server and prints it in the console

This commit is contained in:
Maier
2019-08-30 13:29:12 -04:00
parent 0d27d2913b
commit df492f7187
4 changed files with 20 additions and 11 deletions

View File

@@ -6,7 +6,7 @@ const app = express();
const server = http.Server(app);
const io = socketIO(server);
var activeGames = [];
var activeGames = {};
app.set('port', 5000);
app.use('/static', express.static(__dirname + '/static')); // Routing
@@ -34,14 +34,17 @@ server.listen(5000, function() {
// Add the WebSocket handlers
io.on('connection', function(socket) {
console.log('Client connected.');
socket.on('newGame', function(game) {
activeGames.push(game);
activeGames[game.accessCode] = game;
});
socket.on('joinGame', function(playerInfo) {
activeGames[activeGames.findIndex((game) => game.accessCode === playerInfo.code)].players.push(playerInfo.name);
activeGames[Object.keys(activeGames).find((key) => key === playerInfo.code)].players[socket.id] = playerInfo.name;
console.log("Player " + playerInfo.name + " has joined the game");
});
console.log('games: ', activeGames);
socket.on('requestState', function(data) {
console.log(data);
console.log(activeGames[Object.keys(activeGames).find((key) => key === data.code)]);
socket.emit('state', activeGames[Object.keys(activeGames).find((key) => key === data.code)]);
});
});

View File

@@ -1,5 +1,10 @@
const socket = io();
var games = [];
socket.on('message', function(data) {
console.log(data);
var currentGame = null
socket.on('state', function(game) {
currentGame = game;
console.log(currentGame);
});
window.onload = function() {
socket.emit('requestState', {code: sessionStorage.getItem("code")});
}

View File

@@ -1,6 +1,7 @@
const socket = io();
document.getElementById("join-btn").addEventListener("click", function() {
sessionStorage.setItem("code", document.getElementById("code").value)
const playerInfo = {name: document.getElementById("name").value, code: document.getElementById("code").value};
socket.emit('joinGame', playerInfo);
window.location.replace('/' + document.getElementById("code").value);

View File

@@ -83,16 +83,16 @@ function createGame() {
code += charPool[getRandomInt(61)]
}
console.log(code);
let id = socket.id
const game = new Game(
code,
gameSize,
deck,
document.getElementById("time").value,
[document.getElementById("name").value]
{ [socket.id]: document.getElementById("name").value }
);
socket.emit('newGame', game);
sessionStorage.setItem('accessCode', code);
sessionStorage.setItem('code', code);
window.location.replace('/' + code);
}