【问题标题】:Dice returning 0 and no rolls骰子返回 0 且不掷骰子
【发布时间】:2013-06-08 05:25:18
【问题描述】:
playerDice = new Dice();
int playerDiceNo = playerDice.getfaceofDie();
MessageBox.Show("Your roll" + playerDiceNo);

compDice = new Dice();
int compDiceNo = compDice.getfaceofDie();
MessageBox.Show("Computers roll:" + compDiceNo);

以上是我点击滚动按钮时的方法。 下面是我的骰子课:

class Dice
{
    private int faceofDie;
    public void rollDice()
    {
        Random rollDice = new Random();
        faceofDie = rollDice.Next(1, 7);          
    }
    public int getfaceofDie()
    {
        return faceofDie;
    }
}

我已将 compDice 和 playerDice 的变量声明为:

Dice compDice;
Dice playerDice;

我似乎无法弄清楚为什么两次翻转都返回 0。谁能帮忙?

【问题讨论】:

  • 因为你没有掷骰子
  • 也许是因为你从不掷骰子?
  • 我添加了 playerDice.RollDice();它仍然显示 0
  • 您的代码示例显示错误使用 Random - 请查看重复的问题 - 如果您仍然看到问题更新您的示例并提供更多详细信息。

标签: c# dice


【解决方案1】:

我似乎无法弄清楚为什么两次翻转都返回 0。谁能帮忙?

您永远不会调用rollDice(),因此永远不会设置faceofDie 变量,它的默认值为0。

playerDice = new Dice();
playerDice.rollDice(); // Add this
int playerDiceNo = playerDice.getfaceofDie();
MessageBox.Show("Your roll" + playerDiceNo);

更好的方法是在构造函数中第一次掷骰子,而不是继续创建新的 Random 实例:

class Dice
{
    private static Random diceRoller = new Random();

    private int faceofDie;

    public Dice()
    {
        this.RollDice(); // Roll once on construction
    }

    public void RollDice()
    {   
        lock(diceRoller) 
            faceofDie = diceRoller.Next(1, 7);          
    }

    public int FaceOfDie
    {
        get { return faceofDie; }
    }
}

静态 Random 实例将防止同时实现的多个骰子获得相同的种子(因为它们都将共享一个随机数),这将有助于使您的结果更加一致。这也转移到标准 C# 约定,并且可以像这样使用:

playerDice = new Dice();
int playerDiceNo = playerDice.FaceOfDie;
MessageBox.Show("Your roll" + playerDiceNo);

compDice = new Dice();
int compDiceNo = compDice.FaceOfDie;
MessageBox.Show("Computers roll:" + compDiceNo);

【讨论】:

  • @user2326995 我的代码,如上所述,将返回 1 到 6(含)之间的 2 个不同数字 - 刚刚测试验证。
  • 对不起,我的错误,我的电脑没有显示第二批代码。非常感谢您的帮助,这非常有效。
猜你喜欢
  • 2018-09-08
  • 1970-01-01
  • 2018-06-30
  • 1970-01-01
  • 2012-02-29
  • 2012-03-24
  • 2015-06-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多