Home > Back-end >  Changing the player class every turn in a loop
Changing the player class every turn in a loop

Time:10-26

I need some kind of class or structure to hold data for 4 players in a simple game. How can I change the player class in every turn during the loop?

I mean something similar to this, where in every turn of a loop some instructions are chaning the data in the class of each player. Is there any effortless way to do this instead of creating many ifs?

internal class Program
{
    private static void Main(string[] args)
    {
        Player player1 = new Player();
        Player player2 = new Player();
        Player player3 = new Player();
        Player player4 = new Player();

        int playerTurn = 1;

        while(true)
        {
            //some instructions to change the data for example
            //player(playerTurn).x = 1 
        }

    }
}
class Player
{
    public int x = 0;
    public int y = 0;
}

CodePudding user response:

Whenever you have numbered variables like this:

Player player1 = new Player();
Player player2 = new Player();
Player player3 = new Player();
Player player4 = new Player();

What you probably want is a collection. For example:

var players = new List<Player>
{
    new Player(),
    new Player(),
    new Player(),
    new Player()
};

Then you can loop over the list, change specific elements therein, etc.

In your specific case, it looks like you want to access the specific Player by an index:

//player(playerTurn).x = 1

You can do this with the list index:

players[playerTurn].x = 1;

Though if the list is ever sorted, that index is gone. In this case you might instead use a Dictionary<int, Player>. For example:

var players = new Dictionary<int, Player>
{
    { 1, new Player() },
    { 2, new Player() },
    { 3, new Player() },
    { 4, new Player() }
}

In this case each Player object is always and consistently uniquely identified by that integer value. And the usage is the same:

players[playerTurn].x = 1;

Alternatively, you might create a unique identifier on the Player itself. For example, suppose it has an ID property that you can set:

var players = new List<Player>
{
    new Player { ID = 1 },
    new Player { ID = 2 },
    new Player { ID = 3 },
    new Player { ID = 4 }
};

In this case you can still use the more generically versatile List<Player> structure, and query it to find the specific Player:

players.Single(p => p.ID == playerTurn).x = 1;

There are other collection types you can use. You could even take it a step further and create a custom PlayerList object which internally contains a collection, the current "turn", and other information about the list of players. But overall the point is that collection types are useful when you have a series of objects.

  • Related