zondag 18 november 2007

Dealing The Cards

One of the most important tasks of the dealer is to deal the cards to either the board or the players. Every player gets one card from the dealer and after the first card is dealt to every player at the table, the same procedure is repeated. This way we end up each player having two pocket cards.

Before the flop, turn and river is dealt, a card has to be burned. This means that we remove the top card from the deck. The flop consists of three cards, unlike the turn and the river which are only one card.

What information can we extract from these rules? Obviously, we need to create a Player class and a Board class. Hierarchically the Board and Player classes both have a list of Card classes. The Board class has a list of Player classes. The dealer is the head of the Board class.

Besides that, it should be possible for the Dealer class to burn a card and deal cards in various stages of the hand.

I'll not explain every addition and change, but take some excerpts from the changes. To see every change, download the entire solution below.

First of all, I will show you the cardburning mechanism. It's no complicated matter, just remove the first item in the list:
private void BurnCard()
{
if (cards == null)
{
throw new InvalidOperationException();
}

cards.RemoveAt(0);
}

To make the dealer the head of the board, I have changed the constructor of the Dealer class to accept the Board class. Also I have encorporated an enum for defining the stage of the hand in de Dealer class.

Below I will show you how to deal the cards to the players and the board:
public void Deal(StageEnum stage)
{
if (cards == null)
{
throw new InvalidOperationException();
}

if (board == null)
{
throw new InvalidOperationException();
}

if (board.Players == null || board.Players.Count < 2)
{
throw new InvalidOperationException();
}

int iCardsToDeal = 0;
switch (stage)
{
case StageEnum.PreFlop:
Deal(board.Players, 2);
break;

case StageEnum.Flop:
Deal(board, 3);
break;

case StageEnum.Turn:
Deal(board, 1);
break;

case StageEnum.River:
Deal(board, 1);
break;
}
}

private void Deal(List players, int cardCount)
{
for (int i = 0; i < cardCount; i++)
{
foreach (Player p in players)
{
p.Cards.Add(cards[0]);
cards.RemoveAt(0);
}
}
}

private void Deal(Board board, int cardCount)
{
BurnCard();
board.Cards.AddRange(cards.GetRange(0, cardCount));
cards.RemoveRange(0, cardCount);
}

That was easy :-). In the next post I will discuss how to evaluate the hands and determine the winner!

Download entire solution

Geen opmerkingen: