gpt4 book ai didi

c# - 所有值都在没有断点的情况下更改

转载 作者:行者123 更新时间:2023-11-30 20:35:14 25 4
gpt4 key购买 nike

我试图在 wpf 中进行简单的 Yatsy 游戏,但遇到了一个奇怪的问题。基本上,当在 UI 中单击按钮重新滚动时,将调用 UpdateLogic() 方法。该方法循环遍历骰子列表,应该随机且单独地更新每个值和图像链接。

这是奇怪的部分。如果我在没有 breakboint 或已发布的 .exe 文件的 Debug模式下像往常一样运行它,所有值和图像链接总是获得相同的值。如果我在带有断点的 Debug模式下运行并逐步完成对新值的请求,它会按预期工作。

有人有什么建议吗?

namespace Yatzy{

public partial class MainWindow : Window
{
private DiceManager dm;
private List<BitmapImage> sidesToDisplay = new List<BitmapImage>();

public MainWindow()
{
InitializeComponent();
CreateObjects();

for (int i = 0; i < 6; i++)
{
var side = new BitmapImage();
sidesToDisplay.Add(side);
sidesToDisplay[i].BeginInit();
sidesToDisplay[i].UriSource = new Uri(@"Images/Side" + (i+1) +".png", UriKind.Relative);
sidesToDisplay[i].EndInit();
}
}

private void CreateObjects()
{
dm = new DiceManager();
dm.GenerateDices();
}

private void button_Click(object sender, RoutedEventArgs e)
{
UpdateLogic();
}

private void UpdateLogic()
{
foreach (Dice dice in dm.AllDices)
{
dice.SetNewValue(sidesToDisplay);
}

Dice1.Source = dm.AllDices[0].sideToDisplay;
Dice2.Source = dm.AllDices[1].sideToDisplay;
Dice3.Source = dm.AllDices[2].sideToDisplay;
Dice4.Source = dm.AllDices[3].sideToDisplay;
Dice5.Source = dm.AllDices[4].sideToDisplay;
}
}

public class DiceManager
{
public List<Dice> AllDices { get; set; }

public DiceManager()
{
AllDices = new List<Dice>();
}

public void GenerateDices()
{
for (int i = 0; i < 5; i++)
{
AllDices.Add(new Dice());
}
}
}

public class Dice
{
public int Value { get; set; }
public BitmapImage sideToDisplay { get; set; }

public void SetNewValue(List<BitmapImage> imageList)
{
Value = new Random().Next(1, 7);
sideToDisplay = imageList[Value - 1];
}
}

}

最佳答案

Random 实例使用从系统时钟获取的种子值进行初始化。当您在紧密循环中创建新的 Random 实例时,这会产生问题。这些实例是使用相同的时钟值生成的,因此它们返回相同的数字序列。

诀窍是为所有骰子创建一个 Random 实例并在该实例上调用 Next。

public class Dice
{
public int Value { get; set; }
public BitmapImage sideToDisplay { get; set; }

public void SetNewValue(List<BitmapImage> imageList, int diceValue)
{
Value = diceValue;
sideToDisplay = imageList[Value - 1];
}
}

and in the UpdateLogic

private void UpdateLogic()
{
Random rnd = new Random();
foreach (Dice dice in dm.AllDices)
{
dice.SetNewValue(sidesToDisplay, rnd.Next(1,7));
}
....
}

关于c# - 所有值都在没有断点的情况下更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38282122/

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