12.07.2015 Views

COPYRIGHT 2008, PRINCETON UNIVERSITY PRESS

COPYRIGHT 2008, PRINCETON UNIVERSITY PRESS

COPYRIGHT 2008, PRINCETON UNIVERSITY PRESS

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

344 chapter 13Conway in the 1970s, is Conway’s Game of Life. In this, cells with value 1 are alive,while cells with value 0 are dead. Cells grow according to the following rules:1. If a cell is alive and if two or three of its eight neighbors are alive, then the cellremains alive.2. If a cell is alive and if more than three of its eight neighbors are alive, then thecell dies because of overcrowding.3. If a cell is alive and only one of its eight neighbors is alive, then the cell diesof loneliness.4. If a cell is dead and more than three of its neighbors are alive, then the cellrevives.A variation on the Game of Life is to include a “rule one out of eight” that a cellwill be alive if exactly one of its neighbors is alive, otherwise the cell will remainunchanged. The program OutofEight.java (Listing 13.2) starts with one live cell atthe center of the 3-D array cell[34][34][2] and grows on your screen from there.✞☎/ / Game of the life with 1 out of 8 ruleimport java . io .∗ ;public class OutofEight {public static void main ( String [] argv ) throws IOException {int cell [][][]=new int [34][34][2] ,i , r , j , alive ;for ( j = 0; j < 33; j++ ) { // Initial state of cellsfor ( i = 0; i < 33; i++ ) cell [ j ][ i ][0] = 0;cell [16][16][0] = 1;for ( i = 0; i < 33; i ++) System . out . print (" "+cell [ j ][ i ][0]) ;System . out . println ("" );} // jfor ( r = 0; r < 10; r++ ) {for ( j = 1; j < 32; j++ ) {for ( i = 1; i < 32; i++ ) {alive=0;if ( cell [i−1][j ][0] == 1 ) alive = alive + 1;if ( cell [i+1][ j ][0] == 1 ) alive = alive + 1;if ( cell [i ][j −1][0] == 1 ) alive = alive + 1;if ( cell [i ][ j +1][0] == 1 ) alive = alive + 1;if ( cell [i−1][j −1][0] == 1 ) alive = alive + 1;if ( cell [i+1][j −1][0] == 1 ) alive = alive + 1;if ( cell [i−1][j +1][0] == 1 ) alive = alive + 1;if ( cell [i+1][ j +1][0] == 1 ) alive = alive + 1;if ( cell [i ][ j ][0] == 0 && alive == 1 ) cell [i ][ j ][1]=1;} // i} // jfor ( j =0;j

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!