简体   繁体   English

尝试将 read.txt 文件作为 2D int 数组读取

[英]Trying to read .txt file as a 2D int array

In my current project, I'm procedurally generating a 2D map represented by a 2D array, which is saved as a.txt file.在我当前的项目中,我正在程序上生成一个由二维数组表示的二维 map,该数组保存为 .txt 文件。 Example for a square room map:以方形房间 map 为例:

1 1 1 1 1   
1 0 0 0 1   
1 0 0 0 1   
1 0 0 0 1   
1 1 1 1 1  

Whenever the player dies, I want to read this.txt file, subtract 1 from the position where the player died, and save it again as a different file.每当玩家死亡时,我想读取 this.txt 文件,从玩家死亡的 position 中减去 1,然后将其再次保存为不同的文件。 I tried using File.ReadAllText() and then splitting the text by new lines and whitespaces, I also tried ReadAllLines() and separating the lines into other arrays, but in both cases it returns index out of bounds.我尝试使用 File.ReadAllText(),然后用新行和空格分割文本,我还尝试了 ReadAllLines() 并将这些行分成其他 arrays,但在这两种情况下,它都会返回超出范围的索引。 This is the code as it is now:这是现在的代码:

int[,] deathMatrix = new int[mapReference.width, mapReference.height];//always the same size as the map, in the given example it would be 5x5
        string input = "Assets/deathMatrix_" + mapReference.seed + ".txt";
        if (File.Exists(input))//trying to read .txt into "deathMatrix" 2D array
        {
            String[] lines = File.ReadAllLines(input);
            
            for(int n = 0; n < lines.Length; n++)
            {
                String[] integerStrings = lines[n].Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                for (int k = 0; k < integerStrings.Length; k++)
                {
                    deathMatrix[n, k] = int.Parse(integerStrings[k]); //index out of bounds happens in this line
                }
            }
            File.Delete(input);
        }
        else
        {
            deathMatrix = mapReference.map;//if file does not exist, simply loads map, works correctly
        }

The part where it saves a 2D int array is working correctly, I just need help with this reading and decrementing, because I'm currently unable to see why index goes out of bounds since "integerStrings" should be the correct size after reading.它保存 2D int 数组的部分工作正常,我只需要读取和递减的帮助,因为我目前无法看到为什么索引超出范围,因为“integerStrings”在读取后应该是正确的大小。 I hope i made my problem clear, thanks in advance.我希望我把我的问题说清楚了,提前谢谢。

I think I'd hand this off, tbh;我想我会放弃这个,tbh; shooing data into a text form and back into C# object form is the job of a serializer library.将数据转换为文本形式并返回 C# object 形式是序列化程序库的工作。 Assuming you don't actually care about the specifics of what the data in the file looks like, because you are only ever going to load and edit it in C#, you can simply add a reference to Newtonsoft.Json, and do:假设您实际上并不关心文件中数据的具体内容,因为您只会在 C# 中加载和编辑它,您可以简单地添加对 Newtonsoft.Json 的引用,然后执行以下操作:

File.WriteAllText(path, JsonConvert.SerializeObject(deathMatrix));

int[,] deathMatrix = JsonConvert.DeserializeObject<int[,]>(File.ReadAllText(path));

A 3x3 matrix would end up looking like this inside:一个 3x3 矩阵最终会在内部看起来像这样:

[[0,0,0],[0,0,0],[0,0,0]]

If your code is generating a map elsewhere, that other place will need to write the file like this in order for it to be readable by this process here.如果您的代码在其他地方生成 map,则其他地方将需要像这样编写文件,以便此处的此过程可以读取它。 At some point if you want to store more than just an int[,] the serializer will take it in its stride.在某些时候,如果您想存储的不仅仅是一个int[,] ,那么序列化程序会从容应对。 Maybe you'll have an array of map squares with buried treasure, number of deaths, type of terrain.. For example like this也许你会有一系列 map 方块,里面有埋藏的宝藏、死亡人数、地形类型。例如像这样

If you do want the file to look pretty inside, you can ask the serializer to format it indented (lets say if you wanted to edit it in notepad, and have an easier life), or you could even load it into some editor that undertands JSON, format it, edit it, save it, and the serializer will still be able to load it, because it's more robustly delimited than the example file如果您确实希望文件在内部看起来很漂亮,您可以要求序列化程序将其格式化为缩进(假设您想在记事本中编辑它,并拥有更轻松的生活),或者您甚至可以将它加载到一些可以理解的编辑器中JSON,格式化它,编辑它,保存它,序列化器仍然可以加载它,因为它比示例文件更健壮地分隔

int[,] deathMatrix = new int[mapReference.width, mapReference.height];
string path = "Assets/deathMatrix_" + mapReference.seed + ".txt";
String input = File.ReadAllText( path );

int i = 0, j = 0;

foreach (var row in input.Split('\n'))
{
    j = 0;
    foreach (var col in row.Trim().Split(' '))
    {
        deathMatrix[i, j] = int.Parse(col.Trim());
        j++;
    }
    i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM