I'm trying to make a game of life in java using a matrix of booleans, but when i try to read all the neighboors of one one point the return of the position nearby is always false for some reason... Any clues? My idea is to use the if expression to increment a counter and use that to update the matrix.
public void create() {
setDefaultFontSize( 20 );
grade = new boolean[DIMENSAO_GRADE][DIMENSAO_GRADE];
tempoAtualizacao = 0.4;
mostrarAjuda = true;
prepararCenarioInicial();
}
This part is the function that create some variables and a instance of the grade
private void prepararCenarioInicial() {
executando = false;
for ( int i = 0; i < DIMENSAO_GRADE; i++ ) {
for ( int j = 0; j < DIMENSAO_GRADE; j++ ) {
grade[i][j] = false;
}
}
int iIni = DIMENSAO_GRADE / 2 + 2;
int jIni = DIMENSAO_GRADE / 2;
// glider
grade[iIni][jIni] = true;
grade[iIni+1][jIni+1] = true;
grade[iIni+2][jIni-1] = true;
grade[iIni+2][jIni] = true;
grade[iIni+2][jIni+1] = true;
}
I also create a glider, which means there are true values in the matrix
private void geraGrade(int i, int j){
int somaVivos = 0;
int ni, nj;
for(int x = - 1; x <= 1; x++){
for(int y = - 1; y <= 1; y++){
ni = x + i;
nj = y + j;
if((ni <= 0 || nj <= 0) || (ni > DIMENSAO_GRADE - 1 || nj > DIMENSAO_GRADE - 1))continue;
if(grade[ni][nj] == true && !(x == 0 && y == 0)){
somaVivos++;
}
}
}
System.out.println(somaVivos);
}
But in that block of code the matrix always returns false
Sorry for my bad english, brazilian here
Your bounds checking on ni
and nj
is "off by one" since zero is a valid coordinate; remove the equals sign in your inequality. You can also add the check for the current position when x and y are both zero into that same if
statement:
private void geraGrade(int i, int j){
int somaVivos = 0;
int ni, nj;
for(int x = - 1; x <= 1; x++){
for(int y = - 1; y <= 1; y++){
ni = x + i;
nj = y + j;
if(ni < 0 || nj < 0 ||
ni > DIMENSAO_GRADE - 1 ||
nj > DIMENSAO_GRADE - 1 ||
(x == 0 && y == 0) )
{ continue; }
if(grade[ni][nj]){
somaVivos++;
}
}
}
System.out.println(somaVivos);
}