updated getAliveNeighbours so that it works on the borders

This commit is contained in:
Raphaelsav 2024-05-20 17:06:13 +02:00
parent 350665e641
commit 1fa9941eed
1 changed files with 13 additions and 9 deletions

View File

@ -130,6 +130,8 @@ public class Simulator extends Thread {
} }
public int getAliveNeighbors(int x, int y, int radius) { public int getAliveNeighbors(int x, int y, int radius) {
//to compensate for the cell itself being alive or not
int aliveNeighbors = -1; int aliveNeighbors = -1;
if(getCell(x,y) == 0) { if(getCell(x,y) == 0) {
aliveNeighbors++; aliveNeighbors++;
@ -139,10 +141,13 @@ public class Simulator extends Thread {
//for each neighbor //for each neighbor
for(int i = x-radius; i <= x+radius; i++) { for(int i = x-radius; i <= x+radius; i++) {
for(int j = y-radius; j <= y+radius; j++) { for(int j = y-radius; j <= y+radius; j++) {
if(i!=-1 && i!=getWidth()+1 && j!=-1 && j!=getHeight()+1) { //if neighbor is not outside the map
if(getCell(i,j) == 1) { //if alive, add 1 to counter if(getCell(i,j) == 1) { //if alive, add 1 to counter
aliveNeighbors++; aliveNeighbors++;
} }
} }
}
} }
return aliveNeighbors; return aliveNeighbors;
@ -186,24 +191,23 @@ public class Simulator extends Thread {
*/ */
//calculate and set newCells based on cells //calculate and set newCells based on cells
//i started from 1 and ended < to ignore the borders for(int x=0; x <= getWidth();x++) {
for(int x=1; x < getWidth();x++) { for(int y=0; y <= getHeight(); y++) {
for(int y=1; y < getHeight(); y++) {
int status = getCell(x,y); int status = getCell(x,y);
if(status == 1) { if(status == 1) {
cellDies(x, y); cellDies(x, y); //check if cell should die
}else if(status == 0) { }else if(status == 0) {
cellBorns(x, y); cellBorns(x, y); //check if cell should born
} }
} }
} }
//update cells //update cells
for(int x=1; x < getWidth();x++) { for(int x=0; x <= getWidth();x++) {
for(int y=1; y < getHeight(); y++) { for(int y=0; y <= getHeight(); y++) {
int status = getNewCell(x,y); int status = getNewCell(x,y);
setCell(x, y, status); setCell(x, y, status);
} }