[英]How do I find the last value of a randomly generated int in c#?
I'm trying to find both last positions of X and Y of my player in a .NET Core console application.我试图在 .NET Core 控制台应用程序中找到我的播放器的 X 和 Y 的最后位置。
Every time I press W, A, S or D, it randomly generates positions (A and D for X values, W and S for Y values) in a map 1000px by 1000px.每次我按 W、A、S 或 D 时,它都会在 1000 像素 x 1000 像素的地图中随机生成位置(A 和 D 代表 X 值,W 和 S 代表 Y 值)。 The problem is when every time it says the last values, only Y value is correct and X is still random.
问题是每次它说最后一个值时,只有 Y 值是正确的,而 X 仍然是随机的。
How do I find the last value of a randomly generated int (for both X and Y values) in c#?如何在 c# 中找到随机生成的 int (对于 X 和 Y 值)的最后一个值?
do
{
targetPos = Console.ReadKey(true);
if (targetPos.Key != ConsoleKey.Q)
{
playerX = r.Next(0, 1000);
playerY = r.Next(0, 1000);
}
Console.WriteLine(" ");
switch (targetPos.Key)
{
case ConsoleKey.D:
playerX++;
Console.WriteLine("Right - Position X: {0} ", playerX);
Console.WriteLine();
break;
case ConsoleKey.A:
playerX--;
Console.WriteLine("Left - Position X: {0} ", playerX);
Console.WriteLine();
break;
case ConsoleKey.S:
playerY--;
Console.WriteLine("Down - Position Y: {0} ", playerY);
Console.WriteLine();
break;
case ConsoleKey.W:
playerY++;
Console.WriteLine("Up - Position Y: {0} ", playerY);
Console.WriteLine();
break;
case ConsoleKey.Q:
Console.WriteLine("\nLast Position X: {0}", playerX);
Console.WriteLine("\nLast Position Y: {0}", playerY);
Environment.Exit(0);
break;
}
Console.WriteLine(targetPos.Key.ToString());
} while (targetPos.Key != ConsoleKey.Escape);
Because every time you press a key except Q, both x and y get random.因为每次按下 Q 以外的键时,x 和 y 都会变得随机。 I guess what you want is when press A or D random the x position, when press W or S random the y position, so the code should be:
我猜你想要的是当按 A 或 D 随机 x 位置,当按 W 或 S 随机 y 位置,所以代码应该是:
switch (targetPos.Key)
{
case ConsoleKey.D:
case ConsoleKey.A:
playerX = r.Next(0, 1000);
break;
case ConsoleKey.W:
case ConsoleKey.S:
playerY = r.Next(0, 1000);
break;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.