Forum C# Joining the game after disconnection

Joining the game after disconnection

Postby igli1 » October 8th, 2014, 9:40 pm

How to handle the game when 1 of my users wants to reconnect ?
igli1
 
Posts: 38
Joined: June 29th, 2013, 1:12 pm

Re: Joining the game after disconnection

Postby hangar » October 23rd, 2014, 4:58 am

It's really up to your code. Instead of storing data on the Player object, you might want to put it in a dictionary with the key equal to Player.ConnectUserId, a value unique to the user.

Code: Select all
public class PlayerData {
    public Player player;
    public int score = 0;
   
    public PlayerData(Player player)
    {
        this.player = player;
    }
}


Then in the Game<P>:

Code: Select all
private Dictionary<string, PlayerData> playerDataLookup = new Dictionary<string, PlayerData>();

public override void UserJoined(Player player)
{
  PlayerData playerData;
  // have we seen this player before?
  if (playerDataLookup.TryGetValue(player.ConnectUserId, out playerData) {
    // disconnect duplicate player if still around
    if (playerData.player != null) {
        playerData.player.Disconnect();
    }
    playerData.player = player;
    Broadcast("UserReconnected", player.ConnectUserId);
  }
  else {
    // brand new user
    playerData = new PlayerData(player);
    playerDataLookup.Add(player.ConnectUserId, playerData);
    Broadcast("UserJoined", player.ConnectUserId);
  }
}

public override void UserLeft(Player player)
{
    // probably hit an exception joining; ignore
    if (!playerDataLookup.ContainsKey(player.ConnectUserId)) {
        return;
    }

    PlayerData playerData = playerDataLookup[player.ConnectUserId];
    // another player is forcing us out; we've already been cleaned up
    if (playerData.player != player) {
        return;
    }
   
    playerData.player = null;
    Broadcast("UserLeft", player.ConnectUserId);
}
hangar
 
Posts: 8
Joined: September 16th, 2014, 7:00 am


Return to C#