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

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

above is my method for when the roll button is clicked. Below is my dice class:

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

I have stated my variables for compDice and playerDice as :

Dice compDice;
Dice playerDice;

I can't seem to figure out why it's returning 0 for both rolls over & over. can anyone help?

4

1 回答 1

5

我似乎无法弄清楚为什么两次翻转都返回 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);
于 2013-05-02T15:55:09.193 回答