當涉及到二維數組,你有正確的想法與嵌套for循環。這些允許你遍歷每一行然後每列(如果你想象這是一個矩陣)。
使用Console.SetCursorPostion()
方法可以實現更新控制檯視圖。控制檯中的每個字符都有一個X和Y座標,但調用此方法可以將光標置於一個網格參考。調用此方法後,寫入控制檯的任何內容都將從此新位置輸出。
注意:調用Console.SetCursorPostion()
任何輸出後,控制檯不會被清除,只要簡單地將其寫入頂部即可。這意味着如果在調用方法之後你寫的文本比之前的輸出短,你仍然會看到一些舊的輸出。
在你的情況下,每當你的使用進行一次移動時,你實際上可以清除整個控制檯,這可以通過Console.Clear()
來實現。
我已經寫了一個小的演示應用程序,下面的文本從文本文件中讀取網格,該文本文件可以充當井字遊戲板。默認情況下,網格被填充該特定框的座標,這是因爲程序非常粗糙,並使用這些文本值來放置玩家。玩家去的是存儲在一個二維數組,顯示空白值或可以保持'0'/'X'。
一個簡單的讀取線讓用戶輸入座標,然後它將填充答案的二維數組並重新繪製網格。
十字架總是先走!
我希望這個演示程序給出了一個很好的例子,說明如何重新編寫控制檯,並提供一些關於如何使用二維數組實現您的想法的想法。
計劃
static void Main(string[] args)
{
int player = 0;
string[,] grid = new string[3, 3] {{" "," "," "},
{" "," "," "},
{" "," "," "} };
string box = System.IO.File.ReadAllText(@"C:\Users\..\Box.txt");
Console.WriteLine(box);
Console.ReadLine();
while (true)
{
Console.WriteLine("Enter Coordinate in 'x,y' Format");
string update = Console.ReadLine();
if (player == 0)
{
string[] coords = update.Split(',');
var x = int.Parse(coords[0]) - 1;
var y = int.Parse(coords[1]) - 1;
grid[x,y] = " X ";
player++;
}
else
{
string[] coords = update.Split(',');
var x = int.Parse(coords[0]) - 1;
var y = int.Parse(coords[1]) - 1;
grid[x, y] = " 0 ";
player--;
}
UpdateGrid(grid, box);
}
}
public static void UpdateGrid(string[,] grid, string box)
{
Console.Clear();
for (int i = 0; i < grid.GetLength(0); i++)
{
for (int j = 0; j < grid.GetLength(1); j++)
{
box = box.Replace((i + 1) + "," + (j + 1), grid[i, j]);
}
}
// In the case not required as clearning the console default the cursor back to 0,0, but left in
// as an example
Console.SetCursorPosition(0, 0);
Console.WriteLine(box);
}
文本文件
+-----------------+
| 1,1 | 2,1 | 3,1 |
+-----+-----+-----+
| 1,2 | 2,2 | 3,3 |
+-----+-----+-----+
| 1,3 | 2,3 | 3,3 |
+-----------------+
不同的主題,但可能有助於http://stackoverflow.com/questions/38496889/ – fubo