Reputation: 11026
I have the following code which obviously has some duplication. I'm sure this could be removed using a delegate or Action but can't quite grasp it.
anyone got any ideas?
public void DealStartingCards()
{
for (int i = 0; i < 3; i++)
{
foreach (var player in Players)
{
if (player.Hand.FaceDownCards.Count < 3)
{
if (Deck.Count > 0)
player.Hand.FaceDownCards.Add(Deck.TakeTopCard());
}
}
}
for (int i = 0; i < 3; i++)
{
foreach (var player in Players)
{
if (player.Hand.FaceUpCards.Count < 3)
{
if (Deck.Count > 0)
player.Hand.FaceUpCards.Add(Deck.TakeTopCard());
}
}
}
for (int i = 0; i < 3; i++)
{
foreach (var player in Players)
{
if (player.Hand.InHandCards.Count < 3)
{
if (Deck.Count > 0)
player.Hand.InHandCards.Add(Deck.TakeTopCard());
}
}
}
}
InHandCards, FaceUpCards and FaceDownCards are all of type List<Card>
Upvotes: 0
Views: 199
Reputation: 1502106
Taking Oskar's solution and changing it slightly:
private void DealCards(Func<Hand, List<Card>> handProjection)
{
for (int i = 0; i < 3; i++)
{
foreach (var player in Players)
{
List<Card> cards = handProjection(player.Hand);
if (cards.Count < 3)
{
if (Deck.Count > 0)
{
cards.Add(Deck.TakeTopCard());
}
}
}
}
}
public void DealStartingCards()
{
DealCards(hand => hand.FaceDownCards);
DealCards(hand => hand.FaceUpCards);
DealCards(hand => hand.InHandCards);
}
(That's assuming the type of player.Hand
is Hand
- adjust accordingly otherwise, of course.)
Upvotes: 4