so I'm programming Conway's game of life with JavaFX, and I have a problem.
The grid is represented with a Canvas. I made a method that update the canvas after a value changed in the grid, and a method that compute the next generation according to the rules of the cellular automaton.
The next step is to make the loop :
- compute the next generation
- refresh the canvas
- wait for 0.5 sec.
That's where it goes wrong. It's seems that instead of refreshing the canvas and then wait for 0.5 sec, the program wait for the end of the loop to repaint the canvas.
There are my methods :
public void repaintCanvas() {
Double canvasWidth = gridCanvas.getWidth();
Double canvasHeight = gridCanvas.getHeight();
GraphicsContext gc = gridCanvas.getGraphicsContext2D();
gc.clearRect(0, 0, canvasWidth, canvasHeight);
gc.setFill(Color.RED);
gc.strokeRect(0, 0, canvasWidth, canvasHeight);
gc.setFill(Color.BLACK);
Double x, y;
for (int i = 0; i < this.grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j].isAlive()) {
x = j * cellWidth;
y = i * cellHeight;
Cell.display(gc, x.intValue(), y.intValue(), cellWidth.intValue(), cellHeight.intValue());
}
}
}
}
public void computeNextGeneration() {
Cell[][] newGrid = new Cell[grid.length][grid[0].length];
for (int i = 0; i < newGrid.length; i++) {
for (int j = 0; j < newGrid[0].length; j++) {
newGrid[i][j] = opperationOnCell(i, j);
}
}
grid = newGrid;
repaintCanvas();
}
I tried several things, like the TimeLine class, but the way I change the canvas makes it impossible since the TimeLine seems only to change the shapes in time, when repaintCanvas()
replace them (black square = living cell, white square = dead cell).
How can I fix this ?
Thanks in advance for any help.