Search code examples
c#playing-cards

Only Half of a Deck of Cards Being Created


I'm trying to create BlackJack for a final project. Here is my current code:

public class Card
{
    private string face;
    private string suit;

    public Card(string cardFace, string cardSuit)
    {
        face = cardFace;
        suit = cardSuit;
    }

    public override string ToString()
    {
        return face + " of " + suit;
    }
}

Then I have my deck class:

public class Deck
{
    private Card[] deck;
    private int currentCard;
    private const int NUMBER_OF_CARDS = 52;
    private Random ranNum;

    public Deck()
    {
        string[] faces = { "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
        string[] suits = { "Hearts", "Clubs", "Diamonds", "Spades" };         

        deck = new Card[NUMBER_OF_CARDS];
        currentCard = 0;
        ranNum = new Random();
        for (int count = 0; count < deck.Length; count++)
            deck[count] = new Card(faces[count % 13], suits[count / 13]);
    }

    public void Shuffle()
    {
        currentCard = 0;
        for (int first = 0; first < deck.Length; first++)
        {
            int second = ranNum.Next(NUMBER_OF_CARDS);
            Card temp = deck[first];
            deck[first] = deck[second];
            deck[second] = temp;
        }
    }

    public Card DealCard()
    {
        if (currentCard < deck.Length)
            return deck[currentCard++];
        else
            return null;
    }
}

Then I just a a simple Windows Form with two buttons to just shuffle and deal the cards. The output is sent to a label so I can see what is being dealt. Here is that code:

public partial class Form1 : Form
{
    Deck deck = new Deck();

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
    }

    private void buttonDeal_Click(object sender, EventArgs e)
    {
        Card card = deck.DealCard();
        deck.DealCard();
        labelOutput.Text = card.ToString();
    }

    private void buttonShuffle_Click(object sender, EventArgs e)
    {
        deck.Shuffle();
    }
}

Now, when I hit the deal button it crashes after 27 presses. I notice that it is dealing every other card like 3 of clubs, 5 of clubs, 7 of clubs, 9 of clubs, ect.

I can't seem to find the error! Any help would be appreciated!

EDIT: Here is the Error I get when I click it more than 27 times:

Error


Solution

  • In fact your error comes from this. You are dealing two cards while you would like to deal only one.

    It is crashing because you are incrementing by 2 each times you click your counter. 27 * 2 > 52 cards.

    private void buttonDeal_Click(object sender, EventArgs e)
    {
        Card card = deck.DealCard();
        deck.DealCard(); // error here. Duplicated line
        labelOutput.Text = card.ToString();
    }