Each cell can have eight neighboring cells.
Implementation:
|
Program code:
// GameOfLife.java import ch.aplu.jgamegrid.*; import java.awt.Color; import java.util.ArrayList; public class GameOfLife extends GameGrid { private static final int nb = 20; // Number of cells in each direction private static final int nbCreatures = nb * nb; private static final int popSize = 200; // Size of population at start private boolean[][] pop = new boolean[nb][nb]; private Creature[] creatures = new Creature[nbCreatures]; public GameOfLife() { super(nb, nb, 25, Color.red, "sprites/snowwindow.gif"); setSimulationPeriod(1); int k = 0; // Create creature in every cell for (int x = 0; x < nb; x++) { for (int y = 0; y < nb; y++) { creatures[k] = new Creature(); Location loc = new Location(x, y); addActor(creatures[k], loc); creatures[k].hide(); k++; } } reset(); show(); } public void reset() { // All actors are dead for (int i = 0; i < nbCreatures; i++) creatures[i].isAlive = false; // Create the living population randomly for (int i = 0; i < popSize; i++) { Creature creature = (Creature)getOneActorAt(getRandomLocation()); creature.isAlive = true; } act(); } public void act() { // Show the population for (int i = 0; i < nbCreatures; i++) if (creatures[i].isAlive) creatures[i].show(); else creatures[i].hide(); } public static void main(String[] args) { new GameOfLife(); } } // class Creature extends Actor { protected boolean isAlive = false; public Creature() { super("sprites/creature.gif"); } // Every actor applies the population rules to himself public void act() { // Get number of (living) neighbours ArrayList<Actor> neighbours = getNeighbours(1); int nbNeighbours = 0; for (Actor neighbour : neighbours) if (neighbour.isVisible()) nbNeighbours++; // Generation rule: if (isVisible()) // alive { if (!(nbNeighbours == 2 || nbNeighbours == 3)) isAlive = false; // dying } else // dead { if (nbNeighbours == 3) isAlive = true; // become alive } } } |