I am building a console card game in c#.
I have one dealer and 4 players and I want the dealer to play with each player alone. So, I have put the players in a Queue so that they may be served in order.
My problem is when iterating through all the players in the Queue. When I run my logic (seen below), the for loop will only execute 2 times because the playerQueue is decreasing while the i variable is increasing.
Please help me find a way to rectify this.
I attempted a While loop, but it did not work because we manipulate playerQueue.Count().
Queue<Player> playerQueue = new Queue<Player>();
int number_of_players = 4;
/// <summary>
/// Adds new player to Queue
/// </summary>
for (int i = 0; i < number_of_players; i++)
{
Player player = new Player();
playerQueue.Enqueue(player);
}
/// <summary>
/// Get the first player in the playerQueue
/// </summary>
// HERE IS THE PROBLEM
for (int i = 0; i < playerQueue.Count(); i++)
{
System.Console.WriteLine(playerQueue.Count());
System.Console.WriteLine(i);
// Get the first player in the playerQueue
Player PlayerInGame = playerQueue.Dequeue();
// Play the game with the current player in the queue
}
Below, I updated the codebase so that the for loop is no longer dependent on the count within the queue. Instead, it has a condition checking if there are any waiting in line. Please refer to the code below.
Queue<Player> playerQueue = new Queue<Player>();
int number_of_players = 4;
/// <summary>
/// Adds new player to Queue
/// </summary>
for (int i = 0; i < number_of_players; i++)
{
Player player = new Player();
playerQueue.Enqueue(player);
}
/// <summary>
/// Get the first player in the playerQueue
/// </summary>
// HERE IS THE SOLUTION
while(playerQueue.Any())
{
System.Console.WriteLine(playerQueue.Count());
System.Console.WriteLine(i);
// Get the first player in the playerQueue
Player PlayerInGame = playerQueue.Dequeue();
// Play the game with the current player in the queue
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With