I am thinking I might have misunderstood requirements somewhere.
I keep failing on the CountMyNeighbors method. In itself, it is fairly straight forward. Loop through each array object, if the object isn't mined get the surrounding objects.
Because objects will not have a neighbour at each point ie 00 will only have 3 I have a bunch of if statements to check each value doesn't go out of range on each side of the array.
The tip I am getting infers I am not checking every object but I can't see where my numbers are out. I assume it is one of the loops???
Save my sanity, thanks!
package com.codegym.games.minesweeper;
import com.codegym.engine.cell.*;
import java.util.ArrayList;
public class MinesweeperGame extends Game{
private static final int SIDE=9;
private GameObject[][] gameField = new GameObject[SIDE][SIDE];
private int countMinesOnField=0;
public void initialize(){
setScreenSize(SIDE,SIDE);
createGame();
}
private void createGame(){
boolean isMine = false;
for (int x=0;x<SIDE;x++){
for(int y=0;y<SIDE;y++){
if (getRandomNumber(10)<1) {
isMine = true;
countMinesOnField++;
}
gameField[x][y] = new GameObject(y,x, isMine);
setCellColor(x,y,Color.RED);
}
}
countMineNeighbors();
}
private ArrayList<GameObject> getNeighbors(GameObject cell){
ArrayList<GameObject> neighbourList = new ArrayList<GameObject>();
if (cell.x-1>=0){
//row above
if(cell.y-1>=0)
neighbourList.add(gameField[cell.x-1][cell.y-1]);
neighbourList.add(gameField[cell.x-1][cell.y]);
if (cell.y+1<SIDE)
neighbourList.add(gameField[cell.x-1][cell.y+1]);
}
if (cell.y-1>=0){
//same row
neighbourList.add(gameField[cell.x][cell.y-1]);
if (cell.y+1<SIDE)
neighbourList.add(gameField[cell.x][cell.y+1]);
}
if (cell.x+1<SIDE){
//row below
if(cell.y-1>=0)
neighbourList.add(gameField[cell.x+1][cell.y-1]);
neighbourList.add(gameField[cell.x+1][cell.y]);
if (cell.y+1<SIDE)
neighbourList.add(gameField[cell.x+1][cell.y+1]);
}
return neighbourList;
}
private void countMineNeighbors(){
for(int i=0;i<SIDE;i++){
for(int j=0;j<SIDE;j++){
if(!gameField[i][j].isMine){
for(GameObject z:getNeighbors(gameField[i][j])){
if (z.isMine == true)
gameField[i][j].countMineNeighbors++;
}
}
}
}
}
}