只有一半的卡片被创建

时间:2015-12-01 00:02:30

标签: c# playing-cards

我正在尝试为最终项目创建BlackJack。这是我目前的代码:

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;
    }
}

然后我有我的甲板课:

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;
    }
}

然后我只是一个简单的Windows窗体,带有两个按钮,可以随机播放和处理卡片。输出发送到标签,以便我可以看到正在处理的内容。这是代码:

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();
    }
}

现在,当我点击交易按钮时,它会在27次按下后崩溃。我注意到它正在处理所有其他牌,如3个俱乐部,5个俱乐部,7个俱乐部,9个俱乐部等。

我似乎无法找到错误!任何帮助将不胜感激!

编辑:这是我点击超过27次时得到的错误:

Error

1 个答案:

答案 0 :(得分:0)

实际上你的错误来自于此。 你正在处理两张牌,而你只想处理一张。

崩溃是因为你每次点击计数器都会增加2。 27 * 2&gt; 52卡。

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