我的for循环遇到了一些问题。我已经尝试将它放在不同的区域,但仍然没有运气。我正在研究一个随机改变矩形不透明度的项目(我有红色,黄色,蓝色和绿色)。我让项目工作,以便选择一种颜色,提高不透明度,等待,然后降低不透明度。但是,我想重复一遍,循环不会。
这是我的代码:
private int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}
public void Start_Tapped_1(object sender, TappedRoutedEventArgs e)
{
loopthegame(5);
}
public void loopthegame(int amount)
{
for (int i = 0; i < amount; i++) {
startgame();
}
}
public async void startgame()
{
int randomcolor = RandomNumber(1, 8);
switch (randomcolor)
{
case 1:
Blue.Opacity = 1;
break;
case 2:
Red.Opacity = 1;
break;
case 3:
Yellow.Opacity = 1;
break;
case 4:
Green.Opacity = 1;
break;
case 5:
Blue.Opacity = 1;
break;
case 6:
Red.Opacity = 1;
break;
case 7:
Yellow.Opacity = 1;
break;
case 8:
Green.Opacity = 1;
break;
}
await Task.Delay(1000);
Blue.Opacity = 0.25;
Red.Opacity = 0.25;
Yellow.Opacity = 0.25;
Green.Opacity = 0.25;
}
答案 0 :(得分:0)
似乎你的异步应该稍微更新一下:
public void loopthegame(int amount)
{
for (int i = 0; i < amount; i++) {
Task<int> t = startgame();
await t;
}
}
//...
public async Task<int> startgame()
{
int randomcolor = RandomNumber(1, 8);
switch (randomcolor)
{
case 1:
Blue.Opacity = 1;
break;
//...
case 8:
Green.Opacity = 1;
break;
}
await Task.Delay(1000);
Blue.Opacity = 0.25;
Red.Opacity = 0.25;
Yellow.Opacity = 0.25;
Green.Opacity = 0.25;
return randomcolor;
}
答案 1 :(得分:0)
嗯,你需要做你的异步权(稍作修改):
public async void loopthegame(int amount)
{
for (int i = 0; i < amount; i++)
{
// this
await startgame();
}
}
此外:
public async Task startgame()
{
//...
}
答案 2 :(得分:0)
您的问题实际上在您的随机数生成器中。当您创建没有种子的随机数生成器(new Random())时,它使用time作为种子。这样运行得足够快,每次都使用相同的种子,因此RandomNumber每次都返回相同的数字。而不是每次都创建一个新的Random,你应该有一个你多次使用的Random。在构造函数/ main方法中创建一个,并在RandomNumber方法中重复使用它。
使用这段代码可以轻松测试:
for (int i = 0; i < 5; i++)
{
Random random = new Random();
Console.WriteLine(random.Next(1, 8));
}
尝试一下,它将打印相同的值五次。