/** This is the GameOfLife class as it stood at the * end of the 9:30 lecture 6/2/2003, with minor name * changes, and added comments. * The game is essentially complete, except for having * a driver that repeatedly calls update (and print). * You can do this directly from DrJava and observe the result. */ public class GameOfLife_NineThirty { /** Number of rows on the board.*/ final private int ROWS = 6; /** Number of columns on the board. */ final private int COLS = 6; /** The board itself, as an array of "cells". * Each cell has a status: ALIVE or DEAD. */ private int[][] board; /** Cell values */ final private int ALIVE = 1; final private int DEAD = 2; /** Construct a board with all cells "dead". */ public GameOfLife_NineThirty() { board = new int[ROWS][COLS]; for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { board[r][c] = DEAD; } } } /** ASCII art display of the board. */ public void print() { for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { System.out.print(board[r][c]); } System.out.println(); } } /** See how many living neighbor a cell has.*/ public int countNb(int row, int col) { int count = 0; for (int r = row-1; r <= row+1; r++) { for (int c = col-1; c<= col+1; c++) { //Make sure the cell is one that we can and should check. if ( !((r == row) && (c == col)) && r >= 0 && r < ROWS && c >= 0 && c < COLS) { if (board[r][c] == ALIVE) { count = count +1; } } } } return count; } /** Update each cell on the board. (Code in lecture had literal 3 and 6, which have been replaced by constants.) */ public void update() { final int goAliveLimit = 3; final int goDeadLimit = 6; int[][] newBoard = new int[ROWS][COLS]; for (int r = 0; r < ROWS; r++) { for (int c = 0; c < COLS; c++) { int ncount = countNb(r, c); //Following line was missing in the 9:30 code newBoard[r][c] = board[r][c]; if (ncount < goAliveLimit) { //go alive newBoard[r][c] = ALIVE; } if (ncount > goDeadLimit) { //become dead newBoard[r][c] = DEAD; } } } board = newBoard; } //end class }