Search code examples
javalistarraylistarrayindexoutofboundsexception

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.

for (Cell cell: cells){
        if ((cells.get(cells.indexOf(cell) - 1).mine != null)&&((cells.indexOf(cell) - 1) >= 0)) {
            cell.setMine_number(cell.getMine_number() + 1);
        }
        if ((cells.get(cells.indexOf(cell) + 1).mine != null)&&((cells.indexOf(cell) + 1) < 100)) {
            cell.setMine_number(cell.getMine_number() + 1);
        }
        if ((cells.get(cells.indexOf(cell) - 10).mine != null)&&((cells.indexOf(cell) - 10) >= 0)) {
            cell.setMine_number(cell.getMine_number() + 1);
        }
        if ((cells.get(cells.indexOf(cell) + 10).mine != null)&&((cells.indexOf(cell) + 10) < 100)) {
            cell.setMine_number(cell.getMine_number() + 1);
        }
        if ((cells.get(cells.indexOf(cell) - 11).mine != null)&&((cells.indexOf(cell) - 11) >= 0)) {
            cell.setMine_number(cell.getMine_number() + 1);
        }
        if ((cells.get(cells.indexOf(cell) + 11).mine != null)&&((cells.indexOf(cell) + 11) < 100)) {
            cell.setMine_number(cell.getMine_number() + 1);
        }
        if ((cells.get(cells.indexOf(cell) - 9).mine != null)&&((cells.indexOf(cell) - 9) >= 0)) {
            cell.setMine_number(cell.getMine_number() + 1);
        }
        if ((cells.get(cells.indexOf(cell) + 9).mine != null)&&((cells.indexOf(cell) + 9) < 100)) {
            cell.setMine_number(cell.getMine_number() + 1);
        }
    }

Ignore the spaghetti code I always refactor when things work.


Solution

  • 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 20x20. 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:

    boolean isValidIndex(int cellIndex, int offset) {
      // not doing your homework for you, but rest assured
      // this method is easy to implement
    

    that you then use like:

    if (isValidIndex(cells.indexOf(cell), 9))
    

    for example.