gpt4 book ai didi

c# - 骰子返回 0 且没有掷骰

转载 作者:太空宇宙 更新时间:2023-11-03 20:16:29 24 4
gpt4 key购买 nike

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。谁能帮忙?

最佳答案

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

您永远不会调用 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);

关于c# - 骰子返回 0 且没有掷骰,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16342477/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com