gpt4 book ai didi

c# - 掷骰子游戏

转载 作者:太空宇宙 更新时间:2023-11-03 17:14:43 26 4
gpt4 key购买 nike

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

但是,当我掷骰子 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/

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