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.