I'm experiencing a curious issue that seems to involve overwriting array indices after splicing, or at least that's what I suspect. This problem arises in a small game project built using phaser 2 - essentially, it's a multiplayer jumping game aimed at gaining experience with client/server architecture. We're utilizing socket.io and express for this project. The trouble lies on the server side: when a client disconnects, their removal from the player list causes the remaining player(s) to overwrite the disconnected player's index. To debug this, I have been heavily relying on console logs, using a for loop to iterate through the list of players and display their respective socket IDs.
Initially, I considered an aliasing issue within the onNewPlayer(data) function because of duplication in variable names (var currentInfo). I subsequently changed the second object to var info. So, could this be an aliasing problem, or should I investigate elsewhere for the root cause? If necessary, I can provide additional code; thus far, all callbacks related to player creation and movement appear to be functioning correctly. Thank you.
Below is the relevant server-side code:
var players[];
//When a new player is created, save them
function onNewPlayer(data) {
var newPlayer = new Player(data.x, data.y, this.id);
var currentInfo = {
x: newPlayer.x,
y: newPlayer.y,
id: newPlayer.id,
};
for(i = 0; i < players.length; i++) {
//broadcast the new player's information to all other players in the list
this.broadcast.emit("newEnemy", currentInfo);
}
//check if existing players are present, then send their info to the new player
if(players.length > 0) {
for(i = 0; i < players.length; i++) {
var info = {
x: players[i].x,
y: players[i].y,
id: players[i].id,
};
this.emit("newEnemy", info);
}
}
players.push(newPlayer);
for(i = 0; i < players.length; i++) {
console.log(players[i].id);
}
}
function onDisconnect(){
console.log("User " + this.id + " disconnected");
//find the user in the list of players and remove them, then inform the client
for(i = 0; i < players.length; i++) {
if(players[i].id === this.id) {
console.log("removing this player " + this.id);
//TODO trying a different broadcast
this.broadcast.emit("playerDisconnect", this.id);
console.log(players[i].id);
players.splice(i, 1);
}
}
}
Below is the relevant client-side code:
//We've lost connection with the server!
function onSocketDisconnect() {
console.log("Lost connection with server!");
};
//When the server notifies the client that an enemy has disconnected,
//search for it in the enemy list and stop rendering it
function onEnemyDisconnect(data) {
//TODO
for(i = 0; i < enemies.length; i++) {
if(enemies[i].id == data) {
//TODO
console.log("destroying");
enemies[i].destroy();
enemies.splice(i, 1);
}
}
}