Upload
maurice-floyd
View
230
Download
0
Embed Size (px)
Citation preview
עקרונות תכנות מונחה עצמים
GUI - 6תרגול
: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
ButtonPressed – An ActionListener for setting the initial position
MODEL VIEW
Game Class
Board Class
public void next ( ) { int [ ] [ ] lastState = new int [N+2] [N+2] ; for(int i = 1 ; i <= N ; i++){ // copy current state to new array.
for ( int j =1 ; j <= N ; j++){ lastState [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 = countNeighbors(lastState,i+1,j+1); if(count < 2 || count > 3 ){ //check for under-population or overcrowding
killCell(i,j); } if(count == 3) { // check for reproduction reviveCell(i,j); } } }}
private int countNeighbors(int[][] lastState,int x, int y){ int count = lastState[x-1][y-1] + lastState[x-1][y]+lastState[x-1][y+1] // all 3 neighbors left to current cell + lastState[x][y-1] + lastState[x][y+1] // the cell above current and the cell below + lastState[x+1][y-1] + lastState[x+1][y]+lastState[x+1][y+1] ; // all 3 neighbors left to current cell return count;}
private void killCell( int i , int j ){ array[i][j] = 0; buttons[i][j].setIcon( null );}
private void reviveCell( int i , int j ){ array[i][j] = 1; buttons[i][j].setIcon(new ImageIcon( “button.gif” ));}}//end of Board class
ButtonPressed Class