/* * GameOfLife.java * * Created on June 2, 2003, 7:02 AM */ /** * * @author dickey */ public class GameOfLife3 { final private int cellsAcross = 12; final private int cellsDown = 15; /** Codes for alive and dead. NOT private! */ final static int STATUS_ALIVE = 1; final static int STATUS_DEAD = 2; private int lifeThreashhold = 3; private int deathThreashhold = 6; private int[][] board; private GOLDisplay3 viewer; /** Creates a new instance of GameOfLife */ public GameOfLife3() { this.board = new int[cellsDown][cellsAcross]; for(int r = 0; r < cellsDown; r++) { for (int c = 0; c < cellsAcross; c++) { if ((c+r)%3 ==0) { board[r][c] = STATUS_DEAD; } else { board[r][c] = STATUS_ALIVE; } } } viewer = new GOLDisplay3(cellsAcross, cellsDown, this); } public void updateBoard() { int[][] newBoard; newBoard = new int[cellsDown][cellsAcross]; for(int r = 0; r < cellsDown; r++) { for (int c = 0; c < cellsAcross; c++) { newBoard[r][c] = board[r][c]; //determine new status by counting neighbors of one cell int nCount = countLiveNeighbors(r, c); if (nCount <= lifeThreashhold) { newBoard[r][c] = STATUS_ALIVE; } if (nCount >= deathThreashhold) { newBoard[r][c] = STATUS_DEAD; } } } board = newBoard; viewer.repaint(); } private int countLiveNeighbors(final int r, final int c) { int count = 0; for (int i = r-1; i <= r + 1; i++) { for (int j = c-1; j <= c + 1; j++) { if (i >= 0 && i < cellsDown && j >=0 && j < cellsAcross) { if (board[i][j] == STATUS_ALIVE) { count++; } } } } //System.out.print(" " + count); return count; } public void printBoard() { System.out.println("Board looks like this:"); for(int r = 0; r < cellsDown; r++) { for (int c = 0; c < cellsAcross; c++) { if (board[r][c] == STATUS_ALIVE) { System.out.print("A"); } else { System.out.print("."); } } System.out.println(); } } public int cellStatus(int r, int c) { return this.board[r][c]; } public void toggleCell(int r, int c) { if (board[r][c] == STATUS_ALIVE) { board[r][c] = STATUS_DEAD; } else { board[r][c] = STATUS_ALIVE; } } public void runGame() { while (1 == 1) { updateBoard(); try { Thread.sleep(600); } catch (Exception e) { } //printBoard(); } } public static void main (String[] args) { System.out.println("Game of Life"); GameOfLife3 aGame = new GameOfLife3(); int p = 0; try { Thread.sleep(9000); } catch (Exception e) { } while (p >= 0) { //aGame.printBoard(); aGame.updateBoard(); try { Thread.sleep(600); } catch (Exception e) { } p++; } System.out.println("End game"); } //end class GameOfLife }