Also, I would like to mention that the usage of this code is restricted for personal and educational purposes, unless you give me credit for it.
Today I have implemented the Dealer service. This class has the responsibility to hold the Card classes, shuffle the deck and distribute the Cards to either the players or the board.
Create a new Class Library and call it Poker.Services. Add a new class called Dealer. Implement the next two functions in the Dealer class to initialize the deck of cards and shuffle.
private void InitializeCards() { cards = new List<Card>(); for (int i = 0; i < 13; i++) { for (int j = 0; j < 4; j++) { cards.Add(new Card((Card.SuitEnum)j, (Card.ValueEnum)i)); } } } private void ShuffleCards() { List<Card> c = new List<Card>(); Random rnd = new Random(); for (int i = 0; i < 52; i++) { int cpos = rnd.Next(0, cards.Count); c.Add(cards[cpos]); cards.RemoveAt(cpos); } cards = c; } |
To initialize the class, create this constructor:
private List<Card> cards = null; public List<Card> Cards { get { return this.cards; } set { this.cards = value; } } public Dealer() { InitializeCards(); ShuffleCards(); } |
To test the Dealer service, we have to create a new instance of the Dealer class and count the cards. Also, there should be four cards of each value: one for every suit. Create a new Class Library called Poker.Services.Tests and add a new class DealerTests. Add a reference to the nunit.framework assembly and mark the DealerTests class with [TestFixture].
Create a new function TestDeckConsistency which accepts a generic List of type Card:
public void TestDeckConsistency(List<Card> c) { Assert.AreEqual(52, c.Count); for (int i = 0; i < 13; i++) { int counter = 0; for (int j = 0; j < 52; j++) { if (c[j].Value == (Card.ValueEnum)i) { counter++; } } Assert.AreEqual(4, counter); } } |
Add a new test function to call this with a list of cards:
[Test] public void Dealer_NewCardDeck_52Cards4OfEachValue() { Dealer d = new Dealer(); TestDeckConsistency(d.Cards); } |
Done. We now have a working dealer, which shuffles the cards. Click on the link below to download the entire solution, which includes a modified version of the form: it displays the shuffled cards.
Download entire solution
Geen opmerkingen:
Een reactie posten