I'm trying to build a simple Minesweeper application using a 2D vector. First I fill the squares with 1's and 0's (1's meaning mines and 0's meaning clear).
srand(time(NULL));
for (int i = 0; i < battlefield.size(); i++)
{
for (int j = 0; j < battlefield[i].size(); j++)
{
int num = (rand() % 2);
battlefield[i][j] = num;
}
}`
Then, I go through the vector again and count the number of surrounding mines. This is where I'm having my problem. I think when it tries to check a square that is out of bounds, it blows up. However, if fails before any of those checks. If fails when it tries to see if the current square is equal to 1.
for (int i = 0; i < battlefield.size(); i++)
{
for (int j = 0; j < battlefield[i].size(); j++)
{
int count = 0;
if (battlefield[i][j] == 1)//mine square
{
if (battlefield[i - 1][j - 1] != 0)
{
count++;
}
if (battlefield[i][j - 1] != 0)
{
count++;
}
if (battlefield[i + 1][j - 1] != 0)
{
count++;
}
if (battlefield[i - 1][j] != 0)
{
count++;
}
if (battlefield[i + 1][j] != 0)
{
count++;
}
if (battlefield[i - 1][j + 1] != 0)
{
count++;
}
if (battlefield[i][j + 1] != 0)
{
count++;
}
if (battlefield[i + 1][j + 1] != 0)
{
count++;
}
battlefield[i][j] = count;
}
}
I'm not really sure why it is failing there, any ideas?