/* Life */ import java.awt.*; import java.applet.*; import java.awt.event.*; public class life extends Applet implements ActionListener { // applet constants final int SIZE = 25, // represent a region of SIZE-2 X SIZE-2 APPLETSIZE = 350, DEAD = 0, ALIVE = 1, xOff = 10, yOff = 30, EDGE = (APPLETSIZE - yOff)/SIZE; // instance variables Button god = new Button("God"); int cell[][] = new int[SIZE][SIZE], newCell[][] = new int[SIZE][SIZE]; // all cells initially are DEAD public void init() { add(god); god.addActionListener( this ); // Initialize life board. for (int i = 1; i < SIZE-1; i++) for (int j = 1; j < SIZE-1; j++) cell[i][j] = (Math.random() < 0.5) ? 0 : 1; } public void paint(Graphics g) { // Paint everything DEAD g.setColor(Color.blue); g.fillRect(xOff, yOff, EDGE*SIZE, EDGE*SIZE); // Paint ALIVE cells g.setColor(Color.red); for (int i = 1; i < SIZE-1; i++) for (int j = 1; j < SIZE-1; j++) if (cell[i][j] == ALIVE) g.fillOval(xOff + j*EDGE, yOff + i*EDGE, EDGE, EDGE); } // process button click public void actionPerformed(ActionEvent e) { next(); repaint(); } // Compute next generation void next() { int count; for (int i = 1; i < SIZE-1; i++) for (int j = 1; j < SIZE-1; j++) { count = cell[i-1][j-1] + cell[i-1][j] + cell[i-1][j+1] + cell[i][j-1] + cell[i][j+1] + cell[i+1][j-1] + cell[i+1][j] + cell[i+1][j+1]; switch (count) { case 0: case 1: case 4: case 5: case 6: case 7: case 8: // no birth; death from loneliness or overcrowding newCell[i][j] = DEAD; break; case 3: // birth; no death newCell[i][j] = ALIVE; break; case 2: newCell[i][j] = cell[i][j]; break; } } for (int i = 1; i < SIZE-1; i++) for (int j = 1; j < SIZE-1; j++) cell[i][j] = newCell[i][j]; } }