[英]Replacing specific values in a string array
我对该程序的目标是创建一个用户在其中浏览的网格。 到目前为止,我已经创建了网格,但是我仍然坚持如何使用网格,以便在数组字符串[3,6]的任何位置上都可以用播放器符号“ P”替换“-”之一,并且每次播放器移动控制台后,将打印播放器的位置。
例如。 我希望播放器从字符串[2,5]开始,“-”将替换为“ P”,并且在播放器将[-2,5]移至“-”之后返回。
但我的主要重点是找出如何用播放器替换阵列的任何点。
希望很清楚
string[,] table = new string[3,6] { {"-","-","-","-","-","-"},
{"-","-","-","-","-","-"},
{"-","-","-","-","-","-"}};
int rows = grid.GetLength(0);
int col = grid.GetLength(0);
for (int x = 0; x < rows; x++)
{
for (int y = 0; y < col; y++)
{
Console.Write ("{0} ", grid [x, y]);
}
Console.Write (Environment.NewLine + Environment.NewLine);
}
我尝试使用.Replace,但到目前为止没有成功
我会做这样的事情:
private static int playerX, playerY;
public static void MovePlayer(int x, int y)
{
table[playerX, playerY] = "-"; //Remove old position
table[x, y] = "P"; //Update new position
playerX = x; //Save current position
playerY = y;
UpdateGrid();
}
您所要做的就是将元素设置为"P"
以对其进行更改,没什么好看的。
要更新网格,您有两个选择,要么重新绘制所有内容,要么设置光标位置并更改字符。
例:
SetCursorPosition(playerX, playerY);
Console.Write("-");
SetCursorPosition(x, y);
Console.Write("P");
或者,使用您现在拥有的代码再次调用它以重写所有内容。
另一种方法是通过使用Console.SetCursorPosition()将玩家吸引到正确的位置-有关示例,请参阅我的博客文章 。
或者,您可以完全删除网格:
Point playerLocation = new Point(10, 10);
Size boundary = new Size(20, 20);
void Draw()
{
for (int y = 0; y < boundary.Height; y++)
for (int x = 0; x <= boundary.Width; x++)
Console.Write(GetSymbolAtPosition(x, y));
}
string GetSymbolAtPosition(int x, int y)
{
if (x >= boundary.Width)
return Environment.NewLine;
if (y == playerLocation.Y && x == playerLocation.X)
return "P";
return "-";
}
这样,您就不必更新网格即可更新屏幕。 当您更改玩家的位置时,它将在下一次抽奖时更新屏幕。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.