【问题标题】:Only Half of a Deck of Cards Being Created [closed]一副牌只有一半被创造出来[关闭]
【发布时间】:2015-12-01 00:02:29
【问题描述】:

我正在尝试为最终项目创建二十一点。这是我当前的代码:

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

【问题讨论】:

  • 崩溃是什么意思?是否抛出异常,如果是,是什么异常类和什么消息?也就是说,看起来 DealCard 在 buttonDeal_Click 中被调用了两次。
  • 请使用崩溃时得到的错误输出更新您的问题。
  • 二十一点的牌类应该有一个花色、等级(整数)值。皇后仍然是皇后(12),但值为 10;同样,Stack&lt;Card&gt; 对于甲板(鞋)比阵列更合适。你的shuffle也有问题

标签: c# playing-cards


【解决方案1】:

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

它崩溃了,因为每次单击计数器时都会增加 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2012-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多