Game programming with Java
HomeAufgabennPrintJava-Online

Game of Live


A population grows after the following rules:

Each cell can have eight neighboring cells.

  • each cell with only one or no neighbor dies of loneliness
  • each cell with 4 or more neighbors dies of overpopulation
  • each living cell with 2 or 3 neighbors survives
  • each dead cell with 3 neighbors is resurrected

Implementation:
Each cell has an actor of the class Creature. If the cell is alive the actor is visible, otherwise it is hidden.

 

 

 

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 = 0;
    // Create creature in every cell
    for (int = 0; x < nb; x++)
    {
      for (int = 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 = 0; i < nbCreatures; i++)
      creatures[i].isAlive = false;
    // Create the living population randomly
    for (int = 0; i < popSize; i++)
    {
      Creature creature = (Creature)getOneActorAt(getRandomLocation());
      creature.isAlive = true;
    }
    act();
  }

  public void act()
  {
    // Show the population
    for (int = 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 == || nbNeighbours == 3))
        isAlive = false// dying
    }
    else // dead
    {
      if (nbNeighbours == 3)
        isAlive = true;  // become alive
    }
  }
}