[C#] Text File Map into 2D Array

Junior Spellweaver
Joined
Mar 25, 2007
Messages
126
Reaction score
0
Hi, i am having a bit of trouble with loading a map located in a text file into a 2 dimensional array. The map looks like this

PHP:
6,7
#####
#D  ##
#MBB #
##   #
 ##  #
  ##D#
   ###
The 6, and 7, are the dimensions for the array.

The trouble is that when i read the line in, it wont read the spaces so i sometimes get an index out of bounds error, so if anyone could help me read it in properly that would be great.
 
Try somethin like this.. (untested)

Code:
        char[,] ReadMapFile(string filename)
        {
            try
            {
                string[] s = System.IO.File.ReadAllText(filename)
                    .Replace("\r", "\n")
                    .Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
                int d1 = int.Parse(s[0].Split(',')[0]);
                int d2 = int.Parse(s[0].Split(',')[1]);
                char[,] map = new char[d1,d2];
                for (int x = 0; x < d1; ++x)
                    for (int y = 0; y < d2; ++y)
                        map[x, y] = ' ';
                for (int x = 1; x < s.Length && x <= d2; ++x)
                    for (int y = 0; y < d1 && y < s[x].Length; ++y)
                        map[y, x - 1] = s[x][y];
                return map;
            }
            catch
            {
                return null;
            }
        }
 
Back