一副牌只有一半正在制作中

本文关键字:一半 一副 | 更新日期: 2023-09-27 18:25:11

我正试图为最终项目创建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次以上时得到的错误:

错误

一副牌只有一半正在制作中

事实上,您的错误来自于此。你发两张牌,而你只想发一张。

它崩溃了,因为你每次点击计数器都会增加2。27*2>52张牌。

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