c# - 掷骰子游戏

标签 c# arrays dice

它是掷骰子应用程序。我想总结骰子结果并将它们呈现给用户。目前,在我点击“点击掷骰子”按钮后,骰子图像会发生变化。

但是,当我掷骰子 1 时,结果不会加 (+0),而当我掷骰子 2 时,结果只会 (+1)。我不知道我的代码有什么问题:

public partial class PigForm : Form
{
    Image[] diceImages;
    int[] dice;
    Random roll;

    private void rollDieBotton_Click(object sender, EventArgs e)
    {
        RollDice();
    }

    private void RollDice()
    {
        for (int i = 0; i < dice.Length; i++)
        {
            var currentRoll = roll.Next(0, 6);
            dice[i] += currentRoll;
            dicePictureBox.Image = diceImages[currentRoll];
            playersTotal.Text = String.Format("{0}", dice[i]);
        }
    }

    private void PigForm_Load(object sender, EventArgs e)
    {
        diceImages = new Image[6];
        diceImages[0] = Properties.Resources.Alea_1;
        diceImages[1] = Properties.Resources.Alea_2;
        diceImages[2] = Properties.Resources.Alea_3;
        diceImages[3] = Properties.Resources.Alea_4;
        diceImages[4] = Properties.Resources.Alea_5;
        diceImages[5] = Properties.Resources.Alea_6;

        dice = new int[1] { 0 };
        roll = new Random();
    }
}

最佳答案

关于您的代码的几点说明:

  • 如果数组总是包含一个整数,为什么要使用数组?这也使得 for 循环变得毫无用处。使用普通整数并删除循环。
  • Random 类的Next() 方法有两个参数。第一个是包含下界,第二个是独占上界。在您的情况下,这意味着 0 将是一个可能的数字,而 6 永远不会出现。 (MSDN 页面:Random.Next Method (Int32, Int32))

这里对您的代码稍作修改:

public partial class PigForm : Form
{
    Image[] diceImages;
    int dice;
    Random roll;

    private void rollDieBotton_Click(object sender, EventArgs e)
    {
        RollDice();
    }

    private void RollDice()
    {
        var currentRoll = roll.Next(1, 7);
        dice += currentRoll;
        dicePictureBox.Image = diceImages[currentRoll-1];
        playersTotal.Text = String.Format("{0}", dice);
    }

    private void PigForm_Load(object sender, EventArgs e)
    {
        diceImages = new Image[6];
        diceImages[0] = Properties.Resources.Alea_1;
        diceImages[1] = Properties.Resources.Alea_2;
        diceImages[2] = Properties.Resources.Alea_3;
        diceImages[3] = Properties.Resources.Alea_4;
        diceImages[4] = Properties.Resources.Alea_5;
        diceImages[5] = Properties.Resources.Alea_6;

        dice = 0;
        roll = new Random();
    }
}

关于c# - 掷骰子游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23475021/

相关文章:

c++ - 如何将两个负数数组合并为一个数组?

python - 调用函数时“int”对象不可调用

c# - 在具有多个对应名称的枚举值上调用 ToString() 时,什么决定选择哪个名称?

c - 将数组成员与整数进行比较时出现段错误

arrays - 如何使用 vuetify 数据表显示数组的索引?

java - 当任何人达到 100 时,骰子游戏不会停止。我的代码有什么问题吗?

java - 随机掷2个骰子(java)

c# - 处置对象多次错误。 CA2202。有没有更好的办法?

javascript - asp.net 中的 500 内部服务器错误

C++ 库中的 C# 枚举