Reputation: 129
I'm using a Linked List for turn management in my game. I have Players which I iterate through them, however when one player completes the game he needs to be skipped over, which is where I'm failing at.
How can I do this? here is what I have right now:
public Player GetNextPlayer() {
var current = linkedPlayerList.Find(currentPlayer);
Player nextPlayer = current.Next == null ? linkedPlayerList.First.Value : current.Next.Value;
SetCurrentPlayer(nextPlayer);
return nextPlayer;
}
I tried the following but it doesn't work.
Player nextPlayer = current.Next == null
? linkedPlayerList.First(f => !f.RoundCompleted)
: current.Next.List.Where(w=>!w.RoundCompleted).ElementAt(linkedPlayerList.ToList().IndexOf(currentPlayer));
Upvotes: 0
Views: 6739
Reputation: 216358
I would use a loop to check for your condition. Comments in code to explain.
LinkedList<Player> linkedPlayerList = ......;
Player currentPlayer = .......;
public Player GetNextPlayer()
{
// Find the current node
var curNode = linkedPlayerList.Find(currentPlayer);
// Point to the next
LinkedListNode<Player> nextNode = curNode.Next;
// Check if at the end of the list
nextNode = nextNode == null ? linkedPlayerList.First : nextNode;
// Loop stops when we find the condition true or we reach the starting point
while (curNode != nextNode)
{
// Exit if found....
if (!nextNode.Value.RoundCompleted)
break;
// Manage the next node to check for....
nextNode = nextNode?.Next == null ? linkedPlayerList.First : nextNode.Next;
}
SetCurrentPlayer(nextNode.Value);
return nextNode.Value;
}
Upvotes: 1
Reputation: 17964
You can do something like this (add an an extra null check on next):
Player nextPlayer = current.Next.List.FirstOrDefault (x => !.RoundCompleted);
Upvotes: 0