我目前正在开展一个项目,在那里我收到了很多文件,其中包含不同的游戏板。这些板都是正方形(高度和宽度相等)但尺寸不同。这里可以看到一个小例子(15次15):
.-------------.
|xx x xxxxxx |
| xx xxx x|
| xxx xxxx |
| xx xxx x|
| xxxx x x x |
|xx xxx x xx|
| xx @ x xx|
| x x xx x|
| x x xx |
| xxx xx xxx |
| xx xx x|
| xxxxxx xxx |
|xx x x x|
'-------------'
我希望这些文件能够进入二维数组,因此我可以将它们用作游戏板。
但我需要一些帮助阅读并将文件转换为二维数组。到目前为止,我(从Maximilian Gerhardt解决方案获得灵感):
class Program
{
enum FieldElement
{
Free, Mine, Piece, Boarder
}
static void Main(string[] args)
{
public FieldElement[,] Field {get; set;}
public static Program ParseBoard(string board)
{
using (StreamReader sr = new StreamReader(@"C...test.txt"))
{
// Finds number of lines in the example
var lineCount = File.ReadAllLines(@"C...test.txt").Length;
Console.WriteLine(lineCount);
string lines = sr.ReadLine();
var field = new FieldElement[lineCount-1, lineCount-1];
for (int y = 0; y < lineCount-1; y++)
{
for (int x = 0; x < lineCount; x++)
{
switch (lines[y][x])
{
case 'X':
field[x, y] = FieldElement.Mine;
break;
case '|':
case '-':
case '\'':
field[x, y] = FieldElement.Boarder;
break;
case ' ':
field[x, y] = FieldElement.Free;
break;
case '@':
field[x, y] = FieldElement.Piece;
break;
default:
Console.WriteLine("Unrecognized character {lines[y][x]} in line {y} at position {x}");
break;
}
}
}
return new Board() { Field = field };
}
}
}
}
}
总而言之:我想从文本文件到二维数组获得一些帮助。
答案 0 :(得分:1)
基本解析器将如下所示:定义字段元素(例如,作为枚举或类),然后逐行逐字符地解析字符串。
enum FieldElement
{
Free, X, At, Boarder
}
class Board
{
public FieldElement[,] Field {get; set;}
public static Board ParseBoard(string board)
{
string[] lines = board.Split("\n");
var field = new FieldElement[lines[0].Length, lines.Length];
for(int y=0; y < lines.Length; y++)
{
for(int x=0; x < lines[y].Length; x++)
{
switch(lines[y][x]) //that's a char
{
case 'X':
field[x,y] = FieldElement.X; break;
case '|':
case '-':
case '.':
case '\'':
field[x,y] = FieldElememt.Boarder; break;
case ' ':
field[x,y] = FieldElement.Free; break;
case '@':
field[x,y] = FieldElement.At; break;
default:
Console.WriteLine($"Unrecognized character {lines[y][x]} in line {y} at position {x}");
}
}
}
return new Board() { Field = field; };
}
}
答案 1 :(得分:0)
是否正在加载char数组?
var data = File.ReadLines("file path")
.Select(l => l.ToCharArray())
.ToArray();