- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
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/
我刚刚向自己介绍了 WebGL 和 Threejs,作为开始,我正在尝试创建一个 3D 骰子。我已经到了创建立方体的地步,但我真的不知道如何在立方体的面上放置数字,我能找到的只是如何更改颜色。我已经查
这就是我现在得到的...... var max = 7; var min = 1; $('#dice').click(function() { random = Math.floor(Math.r
我是 Unity 的新手,一直在尝试掷骰子。我遇到了一组教程,它们允许我创建一个 3d 模具(模具使用 Rigidbody 和 Mesh Collider)并编写脚本使其在空格键上滚动,如下所示: 骰
我是 JavaScript 新手,我需要一些想法/帮助来了解如何使我的脚本正常工作。所以我们的想法是,你掷两个骰子,通过按下“掷骰子”按钮然后按下重置按钮来重置整个 HTML 中的所有内容。 所以事情
我正在尝试构建一个掷骰子游戏,如果计算机自动掷出一对骰子,并且如果 cpu 掷出 7 或 11,则用户获胜。然而,如果用户掷出 2、3 或 12,他们将自动失败。如果用户滚动任何其他数字(4、5、6、
背景 如此处所述http://www.ericharshbarger.org/dice/#gofirst_4d12 , “先走”骰子是一组四个骰子,每个都有唯一的编号,因此: 任何两个或更多骰子都不会
我是一名优秀的程序员,十分优秀!