Search code examples
javaarraysminesweeper

Java two dimensional array only working as intended with the first row


This code is the bare-bones of a Minesweeper game board class I'm making. However, this only displays the first row of the array when I display the board. I have looked at this code for so long, and can't see where I'm going wrong with the two-dimensional array. Any help is appreciated

public class Board {

 private Cell[][] cells;

    public Board(PApplet p, int rows, int columns, double bombChance) {

        cells = new Cell[rows][columns];

        for (int r = 0; r < cells.length; r++) {

            for (int c = 0; c < cells[r].length; c++) {

                double randomSeed = Math.random();

                if (randomSeed < bombChance) {
                    cells[r][c] = new BombCell(p);
                } else {
                    cells[r][c] = new SafeCell(p);
                }


            }
        }

    }

    public void display() {

        double tempX = 0;
        double tempY = 0;
        double size = 50;

        for (int r = 0; r < cells.length; r++) {
            for (int c = 0; c < cells[r].length; c++) {

                cells[r][c].display(tempX, tempY, size);

                tempX += 50;
            }

            tempY += 50;

        }
    }
}

Solution

  • It appears that you are failing to reset tempX when you start to render the next row.

    This may fix your issue:

    public void display() {
    
        double tempX = 0;
        double tempY = 0;
        double size = 50;
    
        for (int r = 0; r < cells.length; r++) {
            for (int c = 0; c < cells[r].length; c++) {
    
                cells[r][c].display(tempX, tempY, size);
    
                tempX += 50;
            }
    
            tempY += 50;
            tempX = 0;           // <-------------- look here
    
        }
    }