java - I dont get why this code for my Game of Life doesnt work. Can anyone help me? -
the problem when start code game kinda works doesnt behave normal conwys game of life. thought logic section neighbours checked doesnt work should. after long debugging still couldnt find mistake. :)
import java.awt.*; import javax.swing.*; public class gui extends jpanel { private field field; private jframe frame; public gui() { int width = 800, height = 800; frame = new jframe(); frame.setsize(width, height); frame.setlocationrelativeto(null); frame.setvisible(true); frame.add(this); field = new field(this); } public static void main(string[] args) { new gui(); } public void paint(graphics g) { super.paint(g); int j = 0; (int = 0; < 400; i++) { j = 0; (j = 0; j < 400; j++) { if (field.getalive(i, j)) { g.drawrect(2 * j, 2 * i, 2, 2); g.fillrect(2 * j, 2 * i, 2, 2); } } } check(); } public void check() { int j = 0; (int = 1; < 399; i++) { j = 0; (j = 1; j < 399; j++) { if (field.getalive(i, j)) { int x = 0; if (field.getalive(i - 1, j - 1)) { x++; } if (field.getalive(i, j - 1)) { x++; } if (field.getalive(i + 1, j - 1)) { x++; } if (field.getalive(i + 1, j)) { x++; } if (field.getalive(i - 1, j)) { x++; } if (field.getalive(i - 1, j + 1)) { x++; } if (field.getalive(i, j + 1)) { x++; } if (field.getalive(i + 1, j + 1)) { x++; } if (x < 2 || x > 3) { field.setalive(i, j, false); } } else { if (!field.getalive(i, j)) { int x = 0; if (field.getalive(i - 1, j - 1)) { x++; } if (field.getalive(i, j - 1)) { x++; } if (field.getalive(i + 1, j - 1)) { x++; } if (field.getalive(i + 1, j)) { x++; } if (field.getalive(i - 1, j)) { x++; } if (field.getalive(i - 1, j + 1)) { x++; } if (field.getalive(i, j + 1)) { x++; } if (field.getalive(i + 1, j + 1)) { x++; } if (x == 3) { field.setalive(i, j, true); } } } } } repaint(); } } public class field { private gui gui; private int fieldlength = 1; private boolean[][] alive; public field(gui gui) { this.gui = gui; alive = new boolean[400][400]; for(int = 100 ; i<110; i++){alive[100][i] = true; } for(int = 100 ; i<110; i++){alive[i][100] = true ; } } public boolean getalive(int i, int j) { return alive[i][j]; } public void setalive(int i, int j, boolean alive) { this.alive[i][j] = alive; } }
your problem caused because using same board instance checking rules , updating. every iteration should create new board based off old 1 instead of re-using old board.
you should maintain 2 boards @ given time. 1 read , 1 write copy written 1 @ end of each iteration
Comments
Post a Comment