XNA - 从Txt文件读取平铺映射

时间:2013-08-16 14:18:59

标签: arrays xna stream 2d

我一直在实验并环顾互联网,但我还没想出如何从文本文件中读取瓷砖地图。基本上我有一个名为map的数组,但我想从文本文件中加载地图,而不是在类中实现每个级别:/

我正在思考的游戏是一款益智游戏,你是一个角色扮演角色,必须解决谜题才能进入新房间。

那么当我想添加一个新的地图/关卡时,我该如何制作呢?我只需要编写一个新的.txt文件并将其添加到Game1.cs或类似的东西中? 提前致谢:P

2 个答案:

答案 0 :(得分:0)

很容易,要从.txt文件中读取,您只需使用System.IO命名空间中的一些工具:

using (System.IO.Stream fileStream = System.IO.File.Open(Path_String, System.IO.FileMode.Open))
using (System.IO.StreamReader reader = new System.IO.StreamReader(fileStream))
{
    string line = null;
    while (true)
    {
        line = reader.ReadLine();

        //Get Your Map Data

        if (line == null)
            break;
    }
}

或者,要在C#中编写.txt文件,请使用以下代码:

System.IO.StreamWriter writer = new System.IO.StreamWriter(path + "/" + newShow.name + ".txt");
writer.Write(dataToRight);
writer.Close();
writer.Dispose();

编辑:其他信息 - 为了将您的地图数据从文本文件转换为数组,您可以使用类似下面的代码(假设您确实存储了指定的地图数据) https://stackoverflow.com/questions/18271747/xna-rpg-collision-and-camera

List<int[]> temp = new List<int[]>();
List<int> subTemp = new List<int>();

...

string line = null;
while (true)
{
    line = reader.ReadLine();

    while (line.IndexOf(',') != -1)
    {
        subTemp.Add(line[0]);
        line.Substring(1);
    }
    temp.Add(subTemp.ToArray());
    if (line == null)
        break;
}

int[][] mapData = temp.ToArray();

答案 1 :(得分:0)

noamg97的回答正确地描述了如何在.NET中读写文本文件,但值得注意的是,有更简洁的方法来编写他的两个例子:

string[] mapData = File.ReadAllLines(path);

File.WriteAllLines(path, mapData);

假设每个字符代表地图上的一个图块,您可以使用简单的循环快速将上面的mapData数组转换为更方便的格式,以便处理为您的本机数据格式:

var width = mapData[0].Length;
var height = mapData.Length;
var tileData = new char[width, height];
for (int y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
        tileData[x, y] = mapData[y][x];
}

然后您可以使用它来通过简单的查找来确定特定图块的字符。