So, I'm tryng to generating a txt file with a matrix of 0 and 1, where all the borders are 0 and the body of the matrix is randomly filled with both values. It should be a bitMap where 0 is an obstacle and 1 is a possibile node for pathfinding algorythm. The Method should be called multiple times to generate and save in the folder as mush maps as the user want.
I made this class to generate the map:
public static class GenerateText
{
static string obstacle = "0";
static string node = "1";
public static void CreateMap(int x, int y, string name)
{
string path = "Assets/" + name + ".txt";
if(!File.Exists(name + ".txt"))
{
FileStream fs = File.Create(path);
StreamWriter writer = new StreamWriter(fs);
string[,] map = new string[x, y];
for (int i = 0; i < x; ++i)
{
for (int h = 0; h < y; ++h)
{
int randomValue = RandomGenerator.GetRandom(0, 10);
if (randomValue > 6 || i == 0 || h == 0 || i == x || h == y)
{
map[i, h] = obstacle;
}
else
{
map[i, h] = node;
}
}
}
fs.Close();
writer.WriteLine(map);
}
}
}
and the result should be something like this:
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1,1,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0
0,1,1,1,1,1,1,1,1,1,1,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and reach the end, but if i check the solution the file that was supposed to be generated is missing.
I'm new to this kind of things so it's probably a dumb question, but can someone help me?
1- You are closing filestream before you write anything
2- You are trying to write a array . But you send just array object to the file you need the loop for that
public static class GenerateText
{
static string obstacle = "0";
static string node = "1";
public static void CreateMap(int x, int y, string name)
{
string path = Directory.GetCurrentDirectory() + "/" + name + ".txt";
if (!File.Exists(name + ".txt"))//if there is a empty file with this name
{ //function doesnt work make sure you
//delete any empty file
FileStream fs = File.Create(path);
StreamWriter writer = new StreamWriter(fs);
string[,] map = new string[x, y];
for (int i = 0; i < x; ++i)
{
for (int h = 0; h < y; ++h)
{
int randomValue = RandomGenerator.GetRandom(0, 10);
if (randomValue > 6 || i == 0 || h == 0 || i == x || h == y)
{
map[i, h] = obstacle;
}
else
{
map[i, h] = node;
}
}
}
for (int a = 0; a < x; a++)
{
for (int b = 0; b < y; b++)
{
writer.Write(map[a, b]);
}
writer.WriteLine();
}
writer.Close();
fs.Close();
}
}
}