declare neighbors in 3D Game Of Life
in
Programming Questions
•
1 year ago
I'm kinda stuck with my three dimensional implementation of the
game of life. I get very confusing results when trying to figure out the neighbors of each cell. They all end up with a different number of neighbors and none of them has all expected 26. The part in question is the knock() method inside the Cell class. Here's my code so far:
- import processing.opengl.*;
- boolean pressed = false;
- Cell cells[][][];
- int dim = 6, space = 25; //dimension of the cube and spacing between the cells
- void setup() {
- size(600, 600, OPENGL);
- background(200, 100, 0);
- smooth();
- frameRate(24);
- text("created by ChristianGeick 2011", width-200, height-50);
- cells = new Cell[dim][dim][dim];
- for(int x=0; x<dim; x++) {
- for(int y=0; y<dim; y++) {
- for(int z=0; z<dim; z++) {
- cells[x][y][z] = new Cell(x, y, z);
- }
- }
- }
- }
- void mousePressed() {
- pressed = true;
- }
- void draw() {
- if(pressed) {
- background(54, 63, 69);
- translate(width/2, height/2);
- rotateY(radians(frameCount));
- for(int x=0; x<dim; x++) {
- for(int y=0; y<dim; y++) {
- for(int z=0; z<dim; z++) {
- if(cells[x][y][z] != null) {
- cells[x][y][z].live();
- cells[x][y][z].paint();
- }
- }
- }
- }
- }
- }
- class Cell {
- PVector loc;
- int x, y, z;
- boolean alive;
- Cell neighbors[];
- Cell(int a, int b, int c) {
- x = a;
- y = b;
- z = c;
- loc = new PVector((x-dim/2)*space, (y-dim/2)*space, (z-dim/2)*space);
- if(random(1)>0.5) {
- alive = true;
- } else {
- alive = false;
- }
- neighbors = new Cell[27];
- knock();
- }
- //!! this is the part that doesn't seem to work properly !!
- //get all the 26 neighbors
- void knock() {
- int count = 0;
- int xx, yy, zz; //variables for declaring the neighbor
- for(int a=-1; a<=1; a++) {
- for(int b=-1; b<=1; b++) {
- for(int c=-1; c<=1; c++) {
- if(!(a==0 && b==0 && c==0)) { // leave out the actual cell itself
- xx = x+a;
- yy = y+b;
- zz = z+c;
- //cells at the edges reach over to the other side of the grid
- if(x == 0) {
- xx = dim-1;
- }
- if(y == 0) {
- yy = dim-1;
- }
- if(z == 0) {
- zz = dim-1;
- }
- if(x == dim-1) {
- xx = 0;
- }
- if(y == dim-1) {
- yy = 0;
- }
- if(z == dim-1) {
- zz = 0;
- }
- neighbors[count] = cells[xx][yy][zz];
- count++;
- }
- }
- }
- }
- }
- //display cell
- void paint() {
- if(alive) {
- pushMatrix();
- translate(loc.x, loc.y, loc.z);
- int trans = x*10 + y*10 + z*10;
- fill(254, 180, 28, trans);
- noStroke();
- sphereDetail(10);
- sphere(5);
- popMatrix();
- }
- }
- //determine the state of the cell
- void live() {
- int lifes = 0;
- for(int i=0; i<neighbors.length; i++) {
- if(neighbors[i] != null) {
- if(neighbors[i].alive) {
- lifes++;
- }
- }
- }
- if(lifes > 5 && lifes < 10) {
- alive = true;
- } else {
- alive = false;
- }
- }
- }
Thanks for any advice.
1