i am trying to create minesweeper in c# to do this i create an multidimensional array and then randomly pick positions using
Random rand = new Random;
the problem comes when trying to run the code, when i run it it takes an extremely long time to finish, i suspect it is because of the while loop and the if statements, if the rand.Next
keeps getting the same values it could cause the loop to run for a long time. is there something im doing that is afftecting the pseudo randomness of my numbers. code below.
after returning to this questing a while later in an attempt to make it less horrendous it is clear that the reason for the program taking so long to run lies within the
while (counter < numberOfMines)
{
if (Minefield[randomNumber1, randomNumber2] == 9)
{
counter--;
}
else
{
Minefield[randomNumber1, randomNumber2] = 9;
counter++;
}
randomNumber1 = (rand.Next(4)) + 1;
randomNumber2 = (rand.Next(4)) + 1;
}
section of the code. The reason that it was taking so long is that i was treating the while loop like a for loop and taking away from the counter when it was failing to place a mine. this is incorrect and i should have just not added to it.
using System;
class MainClass
{
static void Main(string[] args)
{
int boardSize = 5;
int numberOfMines = 25;
GenerateMinefield(boardSize,numberOfMines);
Console.ReadKey();
}
static int[,] GenerateMinefield(int boardSize, int numberOfMines)
{
int[,] Minefield = new int[boardSize + 2, boardSize + 2];
for (int i = 0; i <= boardSize; i++)
{
for (int j = 0; j <= boardSize; j++)
{
Minefield[j, i] = 0;
}
}
Random rand = new Random();
int randomNumber1 = (rand.Next(4)) + 1;
int randomNumber2 = (rand.Next(4)) + 1;
int counter = 0;
while (counter < numberOfMines)
{
if (Minefield[randomNumber1, randomNumber2] == 9)
{
counter--;
}
else
{
Minefield[randomNumber1, randomNumber2] = 9;
counter++;
}
randomNumber1 = (rand.Next(4)) + 1;
randomNumber2 = (rand.Next(4)) + 1;
}
for (int i = 0; i <= boardSize; i++)
{
for (int j = 0; j <= boardSize; j++)
{
Console.Write(Minefield[j, i]);
}
Console.WriteLine(Minefield[boardSize, i]);
}
return Minefield;
}
}