gpt4 book ai didi

c# 在表单中注册多个按钮点击

转载 作者:太空宇宙 更新时间:2023-11-03 12:06:10 25 4
gpt4 key购买 nike

所以现在我正在制作一个以学习为目的的游戏,玩家点击一个按钮,它会从总分中取走一个随机数。问题是它只工作一次,因为当再次点击它时它会重置。那么如何让它可以多次工作呢?抱歉打扰了。

 public void playerTwo(object sender, EventArgs e)
{
Random rnd = new Random();
int attack = rnd.Next(1, 10);

int playerOneScore = 1000;
int playerOneScores;

playerOneScores = playerOneScore - (1 * attack);


playerOneHealth.Text = playerOneScores.ToString();

最佳答案

将您的代码更改为以下内容。

int playerOneScore = 1000;
public void playerTwo(object sender, EventArgs e)
{
Random rnd = new Random();
int attack = rnd.Next(1, 10);

//int playerOneScore = 1000; <-- don't set playerOneScore inside the method, as this line gets executed with every time calling this method so it again and again gets set to 1000
//int playerOneScores; <-- don't get the meaning of this one, so I removed it and I am changing the playerOneScore field

playerOneScore = playerOneScore - (1 * attack);
playerOneHealth.Text = playerOneScore.ToString();
}

除此之外,您还应该考虑将 Random 变量移到方法之外,因为快速创建 Random 对象会一遍又一遍地为您提供相同的结果。

您可以在此处了解为什么会发生这种情况:Random number generator only generating one random number

因此,我建议将其更改为:

int playerOneScore = 1000;
Random rnd = new Random();
public void playerTwo(object sender, EventArgs e)
{
//Random rnd = new Random(); <-- don't create Random here as it will likey produce the same random number over and over again
int attack = rnd.Next(1, 10);

//int playerOneScore = 1000; <-- don't set playerOneScore inside the method, as this line gets executed with every time calling this method so it again and again gets set to 1000
//int playerOneScores; <-- don't get the meaning of this one, so I removed it and I am changing the playerOneScore field

playerOneScore = playerOneScore - (1 * attack);
playerOneHealth.Text = playerOneScore.ToString();
}

在此处查看实际效果: https://dotnetfiddle.net/djr94j

(我不得不将其更改为静态字段和方法,这对您来说不是必需的)

关于c# 在表单中注册多个按钮点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54891536/

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