I am trying to create a similar model of Conway's game of life in Java, but adapted to some specific conditions and behavoiur of cells. I do not have enough experience in programming so, I will be greateful if you can give me some answers.
I have this code so far:
package project_cells;
import java.util.Random;
public class Field {
public static void main(String[] args) {
int size = 4;
char[][] field = new char[size][size]; // field
char[] cell_type = {'A','B','a','b'}; // fill out vector with cell type
for(int i = 0; i <size; i++ ) { // checking the matrix positions
for (int j = 0; j <size; j++) {
Random rand = new Random();
int celltype_option = rand.nextInt((3-0)+1)+0; // creating a random number from 0 to 3
field[i][j]=cell_type[celltype_option]; // Filling the field with cell types
}
}
System.out.println("Клетки первого поколения"); // checking the first generation of cells
for (int x=0; x < field.length; x++) {
System.out.print("|");
for (int y=0; y < field[x].length; y++) {
System.out.print (field[x][y]);
if (y!=field[x].length-1) System.out.print("\t");
}
System.out.println("|");
}
}
}
With this code I get only the array with the 4 type of cells (A,B,a,b) A and B change its behaviour, a and b don't change.
The issue is that I need to create 3 ways to verify the neighbors: 1. When cell verifies only 4 neighbors (up, right, left, down). 2. When cell verifies 8 surrounding neighbors and 3. When cell verifies any random neighbor.
How can I get such verifications?
The left and right neighbors of x
are x-1
and x+1
. They only exist if they are >= 0
and <= size - 1
:
for (int i = -1; i <= 1; i+= 2) { // i = -1, +1
final int neighborIndex = x + i;
if (neighborIndex >= 0 && neighborIndex < size) {
// ...
}
}
The up/down case can be handled analogously.
To get all eight neighbors, iterate from x-1
to x+1
and the inside it from y-1
to y+1
(again, only if >=0
and < size
) and filter out the center (x, y)
:
for (int xNeighbor = Math.max(0, x - 1); xNeighbor <= Math.min(size - 1, x + 1); xNeighbor += 1) {
for (int yNeighbor = Math.max(0, y - 1); yNeighbor <= Math.min(size - 1, y + 1); yNeighbor += 1) {
if (!(xNeighbor == x && yNeighbor == y)) {
// ...
}
}
}
To get a random neighbor, first count the number of neighbors and then use rand.nextInt(numNeighbors)
to select one.