I have an array which handles all the games being hosting on the server. Users can host games and cancel the host as they please. What I have below seems to work, but I'm not sure if it adds the object to the lowest free index, but it adds them and removes just fine. The code is a bit of a mess so I've commented a lot to help you understand.
var hostingGames = [];
server.em.addListener('hostGame', function(settings)
{
if (hostingGames.length != 0) //If the array that contains all the games being hosted, contains at least 1 game
{
for (i in hostingGames)//Scroll through every game being hosted
{
if(hostingGames[i] != null)//If the current index in the array does contain a game being hosted
{
if(hostingGames[i].userId === settings.userId)//If the user thats trying to host a game, is already hosting a game
{
break; //Then break
}
else if (i == (hostingGames.length - 1))//If hes not hosting a game and all the games have finished being scrolled through
{
hostGame(settings, i + 1); //Then host one in the next avaliable space
}
}
else //If the game is null
{
for(var i = 0; i < hostingGames.length; i++) //Scroll through the list of the games being hosted again
{
if(hostingGames[i] === null) //If theres a free slot
{
hostGame(settings, i); //Host a game
}
}
}
}
}
else
{
hostGame(settings, 0); //If there is no games currently being hosted, host one
}
function hostGame (settings, index)
{
var hostGame = new HostGame();
hostGame.initialise(settings.userId, settings.userName, settings.boardSize, settings.gameMode, settings.gameNote);
hostingGames.splice(index, 0, hostGame);
server.updateGamesList(hostingGames);
server.consoleLog('APP', settings.userName + ' is hosting a game. ID: ' + settings.userId);
}
});
server.em.addListener('cancelHostGame', function(userId, userName)
{
for (i in hostingGames)//For every game
{
if (hostingGames[i] != null) //If its not null
{
if (hostingGames[i].userId === userId) //If that user is hosting a game
{
hostingGames.splice(i, 1); //Remove their game
server.updateGamesList(hostingGames);
server.consoleLog('APP', userName + ' has stopped hosting a game. ID: ' + userId);
}
}
}
});