新的C#呃这里。我正在通过控制台应用程序进行基于文本的冒险。我做了一个地图命令,当你输入“地图”时,它会显示一个地图,其中一个X表示你当前的位置。 Int变量xCoordinate和yCoordinate用于表示地图上的字符位置,每当您键入“go north”或“go south”等时,它将更改为1。地图为13x10,因此您的角色有130个可能的位置。我做了130个不同的if语句,它运行得很好。我的问题是,是否有更有效/更简单的方法来做到这一点。这是我的代码:
public static void Map()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("\n" + xCoordinate + ", " + yCoordinate);
Console.WriteLine("\nTowns are represented by a \"T\". Current location is shown as an \"X\".\n");
Console.ForegroundColor = ConsoleColor.DarkGray;
if ((xCoordinate == -7) && (yCoordinate == -4))
{
Console.Write("[ ][ ][ ][ ][ ][ ][ ][T][ ][ ][ ][ ][ ] 5\n");
Console.Write("[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] 4\n");
Console.Write("[ ][ ][ ][ ][T][ ][ ][ ][ ][T][ ][ ][ ] 3\n");
Console.Write("[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] 2\n");
Console.Write("[ ][ ][T][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ] 1\n");
Console.Write("[T][ ][ ][ ][ ][ ][ ][T][ ][ ][ ][T][ ] 0\n");
Console.Write("[ ][ ][ ][ ][T][ ][ ][ ][ ][ ][ ][ ][ ]-1\n");
Console.Write("[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]-2\n");
Console.Write("[ ][ ][T][ ][ ][ ][T][ ][ ][ ][T][ ][ ]-3\n");
Console.Write("[X][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]-4\n");
Console.Write("-7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5\n\n");
}
Console.ForegroundColor = ConsoleColor.White;
}
同样,我在130个不同的if语句中输入了130次,每次X都在其他地方。我认为会有更好的方法,但我不知道。
答案 0 :(得分:10)
您应该阅读并了解for等循环。
沿线的东西
for(var xCoordinate = -10; xCoordinate <=10; xCoordinate ++)
{
for(var yCoordinate = 5; yCoordinate >= 5; yCoordinate --)
{
if (xCoordinate == ... && yCoordinate == ..)
{
Console.Write("[X]");
}
else
{
Console.Write("[ ]");
}
}
Console.WriteLine();
}
答案 1 :(得分:1)
public static void Map()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("\n" + xCoordinate + ", " + yCoordinate);
Console.WriteLine("\nTowns are represented by a \"T\". Current location is shown as an \"X\".\n");
Console.ForegroundColor = ConsoleColor.DarkGray;
for (int y = 5; y >= -4; y--)
{
for (int x = -7; x <= 5; x++)
{
Console.Write(yCoordinate == y && xCoordinate == x ? "[X]" : "[ ]");
}
Console.WriteLine(" {0}", y);
}
Console.Write("-7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5\n\n");
Console.ForegroundColor = ConsoleColor.White;
}