Here is my code to create a grid with randomly generate mines. Problem is the mines is so diffuse, so when I count the mines for non-mine cells, it mainly have value 1, 2 and nearly don't have value 4, 5 , 6, 7. How to improve this algorithm?
Assume that number of columns, rows and mines are constant.
var r = new Random();
int columns, rows, TotalMine;
int[,] grid = new int[columns, rows];
int MineCount = 0;
int X = 0;
int Y = 0;
// Add Mines (This is so simple, it cause the problem)
while (MineCount++ < TotalMine)
{
do
{
X = r.Next(columns);
Y = r.Next(rows);
}
while (grid[X, Y] == -1);
grid[X, Y] = -1; // -1 = have mine
}
Your algorithm is perfectly fine and will create randomly spread mines (assuming the RNG is good enough).
One way improving I could imagine would be using a Game of Life algorithm to remove extremes, for examle cluttered fields where one field is surrounded by 7 or 8 mines.
Just iterate over all fields and count the surrounding mines (i.e. calculate the fields' numbers). If it's 7 or 8, remove one random mine next to it.
As an alternative, you could use perlin noise to create "clouds" and then only place mines randomly in areas where you've got at least a given "density". This way you can rather easily create bigger areas with nothing in between them.
You could also mix both ideas a bit:
true
or false
).false
(or true
- whatever you choose).