GUI Swing Basic components Event handling Containers Layouts
: GUI סיכום ביניים Swing Basic components Event handling Containers Layouts
Outline Game of Life Painting
Case Study Game of Life
Conway’s Game of Life
Basic Rules Each cell in the grid is either live or dead The user determines the initial positions of all live cells. The game proceeds in rounds. In each round some new organisms born, and others die, according to predefined evolution rules.
Neighbors The neighbors of a cell are the cells that surround it.
Neighbors The neighbors of a cell are the cells that surround it.
Evolution Rules Any live cell with fewer than two live neighbors dies, as if caused by under-population. Any live cell with two or three live neighbors lives on to the next generation. Any live cell with more than three live neighbors dies as if by overcrowding. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction
Program clasess Game – Main class that creates the graphical user interface. Board – A class that represents the game board. Holds an array of integers and an array of buttons MODEL Ø VIEW Button. Pressed – An Action. Listener for setting the initial position
Game Class
Board Class
public void next ( ) { int [ ] last. State = new int [N+2] ; for(int i = 1 ; i <= N ; i++){ // copy current state to new array. for ( int j =1 ; j <= N ; j++){ last. State [i][j] = array[i-1][j-1]; } } // top and buttom row (i = 0, N+1), left and right culomn(j= 0, N+1) initiate to 0 for ( int i = 0 ; i < N ; i++){ // update current state. for(int j < 1; j <= N ; j++ ){ int count = 0; count = count. Neighbors(last. State, i+1, j+1); if(count < 2 || count > 3 ){ //check for under-population or overcrowding kill. Cell(i, j); } if(count == 3) { // check for reproduction revive. Cell(i, j); } } private int count. Neighbors(int[][] last. State, int x, int y){ int count = last. State[x-1][y-1] + last. State[x-1][y]+last. State[x-1][y+1] // all 3 neighbors left to current cell + last. State[x][y-1] + last. State[x][y+1] // the cell above current and the cell below + last. State[x+1][y-1] + last. State[x+1][y]+last. State[x+1][y+1] ; // all 3 neighbors left to current cell return count; } private void kill. Cell( int i , int j ){ array[i][j] = 0; buttons[i][j]. set. Icon( null ); } private void revive. Cell( int i , int j ){ array[i][j] = 1; buttons[i][j]. set. Icon(new Image. Icon( “button. gif” )); } }//end of Board class
Button. Pressed Class
- Slides: 14