Skip to content
Advertisement

Checking adjacent cells in a java ArrayList for minesweeper

I have all my cells stored in an ArrayList and I want to check how many mines they are surrounded by (mines are cells with a not null mine png). I thought of checking the positions -1, +1, -9, +9, -10, +10, -11, +11 relative to each cell and add 1 to a counter inside the cell object. Problem is I get out of bounds and don´t know how to avoid it.

JavaScript

Ignore the spaghetti code I always refactor when things work.

Advertisement

Answer

I thought of checking the positions -1, …

That thought doesn’t work unfortunately.

First of all, you “hardcode” the dimension of your “supposedly 2 dim” list into these numbers. What if you change the grid to 20×20. Then -10 is meaningless.

Then: it is kinda obvious that for plenty of slots, -10 or +10 wont work.

You could create a simple checker method like:

JavaScript

that you then use like:

JavaScript

for example.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement