我这个程序的目标是创建一个用户可以在其中导航的网格。到目前为止,我已经创建了网格,但我一直不知道如何拥有它,以便在数组 string[3,6] 的任何位置我都可以用玩家符号“P”替换“-”之一,并且每次玩家移动控制台会打印玩家的位置。
EG。我希望玩家从字符串[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");
或者,使用您现在拥有的代码再次调用它来重写所有内容。
关于c# - 替换字符串数组中的特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23187940/