【问题标题】:Getting data out of a textfile and feeding it into a 2d array从文本文件中获取数据并将其输入二维数组
【发布时间】:2017-09-10 18:27:49
【问题描述】:

我想让我的游戏中的关卡从文本文件加载并将其加载到二维数组中,这就是关卡文本文件的外观:

0,0,0,0,0,0,0,0,0,0
1,1,1,1,1,1,1,1,1,1
2,2,2,2,2,2,2,2,2,2
3,3,3,3,3,3,3,3,3,3
4,4,4,4,4,4,4,4,4,4
5,5,5,5,5,5,5,5,5,5
6,6,6,6,6,6,6,6,6,6
7,7,7,7,7,7,7,7,7,7
8,8,8,8,8,8,8,8,8,8
9,9,9,9,9,9,9,9,9,9

我希望每个数字都是一个单独的棋子,逗号将充当分隔符,但我不知道如何实际将数据从中获取到我的二维数组中。这是我已经走了多远:

    Tile[,] Tiles;
    string[] mapData;
    public void LoadMap(string path)
    {
        if (File.Exists(path))
        {
            mapData = File.ReadAllLines(path);

            var width = mapData[0].Length;
            var height = mapData.Length;

            Tiles = new Tile[width, height];

            using (StreamReader reader = new StreamReader(path))
            {
                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {                           
                        Tiles[x, y] = new Tile(SpriteSheet, 5, 3, new Vector2(x * 64, y * 64));
                    }
                }
            }
        }
    }

Tiles[x, y] = new Tile() 行中的数字 5 和 3 表示纹理在纹理图中的位置。我想添加一个 if 语句,例如文件中的数字是否在左上角为 0,我希望 Tiles[0, 0] 设置为我的纹理图中的特定行和列。对此的任何帮助将不胜感激,我没有看到它!

【问题讨论】:

    标签: c# arrays dictionary streamreader monogame


    【解决方案1】:

    首先,var width = mapData[0].Length; 将返回字符数组的长度,包括逗号,即 19。看起来您不希望它返回逗号。所以,你应该像这样分割字符串:

    Tile[,] Tiles;
    string[] mapData;
    public void LoadMap(string path)
    {
        if (File.Exists(path))
        {
            mapData = File.ReadAllLines(path);
    
            var width = mapData[0].Split(',').Length;
            var height = mapData.Length;
    
            Tiles = new Tile[width, height];
    
            using (StreamReader reader = new StreamReader(path))
            {
                for (int y = 0; y < height; y++)
                {
                    string[] charArray = mapData[y].Split(',');
                    for (int x = 0; x < charArray.Length; x++)
                    {               
                        int value = int.Parse(charArray[x]);
    
                        ...
    
                        Tiles[x, y] = new Tile(SpriteSheet, 5, 3, new Vector2(x * 64, y * 64));
                    }
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2015-04-16
      相关资源
      最近更新 更多