Stefan Dimeski
Stefan Dimeski

Reputation: 458

Minesweeper neighbor count

I'm trying to replicate Minesweeper and I encountered a problem counting neighbors that are mines. It seems like a very easy thing to implement, but for some reason I'm not getting the desired results everywhere. I have a 1d array of ints representing each tile. I would like a way to get every neighbor of a tile separately considering that it could have variable grid size. Here's what my code is looking like:

int num = 0;

if (i + 1 < 16 && graph[i + 1] == -1)
    num++;
if (i - 1 >= 0 && graph[i - 1] == -1)
    num++;
if (i + 3 < 16 && graph[i + 3] == -1)
    num++;
if (i - 3 >= 0 && graph[i - 3] == -1)
    num++;
if (i + 4 < 16 && graph[i + 4] == -1)
    num++;
if (i - 4 >= 0 && graph[i - 4] == -1)
    num++;
if (i + 5 < 16 && graph[i + 5] == -1)
    num++;
if (i - 5 >= 0 && graph[i - 5] == -1)
    num++;

return num;

and I'm not getting the results I want for the leftmost and rightmost tiles. Also sometimes there is a problem with the downmost and upmost tiles too. My code uses a grid(apparently I called it graph :) ) of fixed size 4x4(int[16]).

Thanks in advance.

Upvotes: 1

Views: 1123

Answers (2)

merlinND
merlinND

Reputation: 855

I think the mistake comes from how you think your data is being stored VS how it is actually stored. If I understand correctly, your code snippet currently looks at several neighbors on the same line (or possibly column) as your ith position.

This answer contains good explanations about how to linearize a 2D grid into a 1D array: Convert a 2D array index into a 1D index

Alternatively, using a 2D array (or better yet, an std::vector<std::vector<int> > would probably makes things much cleaner and less error-prone. The performance costs would be negligible in this case.

Upvotes: 0

rdans
rdans

Reputation: 2157

Your conditions are incorrect. If the player is at the right edge of the grid then i-3 would be the left side of the grid.

To deal with this you could add additional checks to see if you are on an edge. e.g.

if (i - 3 >= 0 && (i+1) % 4 > 0 && graph[i - 3] == -1)
    num++;

You would need similar checks for most of your other if statements (all except for +/- 4).

Upvotes: 1

Related Questions