//****************************************************************************** // life.java: Applet // //****************************************************************************** import java.applet.*; import java.awt.*; import java.util.*; import java.awt.Event; public class life extends Applet { static final int MAXSCALE = 6; Button clear,shake,step,loop; Button[] scale = new Button[MAXSCALE]; Random rnd = new Random(); static final int DRAWPIXELS = 320; static final int GRIDWIDE = 320; static final int GRIDHIGH = 320; static final int REPAINT_TICKS = 100; // 10 times a second boolean[][] state = new boolean[GRIDWIDE][GRIDHIGH]; boolean[][] newState = new boolean[GRIDWIDE][GRIDHIGH]; int gridValue = 80; int[] scaleValue = {10,20,40,80,160,320}; boolean doLoop = false; //--- constructor --- public life(){ clearGrid(); } public void init(){ setLayout(null); resize(320,350); buildTools(); moveTools(); } //--- paint functions --- public void update(Graphics g){ try {paint(g);} catch(Exception ex){ex.printStackTrace();} if (doLoop) { advanceState(); repaint(REPAINT_TICKS); } } public void paint(Graphics g){ int wide,high; g.setColor(Color.white); g.fillRect(0,0,320,400); g.setColor(Color.blue); wide = GRIDWIDE / gridValue; high = GRIDHIGH / gridValue; for (int i=0;i=gridValue) return false; high = GRIDHIGH / gridValue; y = (y-30) / high; if (y<0 || y>=gridValue) return false; state[x][y] = (state[x][y]?false:true); repaint(); return state[x][y]; } public void setState(int x,int y,boolean val){ int wide,high; wide = GRIDWIDE / gridValue; x = x / wide; if (x<0 || x>=gridValue) return; high = GRIDHIGH / gridValue; y = (y-30) / high; if (y<0 || y>=gridValue) return; state[x][y] = val; repaint(); } //--- advance grid --- int[] dx = {0,1,1,1,0,-1,-1,-1}; int[] dy = {-1,-1,0,1,1,1,0,-1}; public void advanceState(){ int i,j,di,dj,dir,count; for (i=0;i=gridValue) continue; dj = j + dy[dir]; if (dj<0 || dj>=gridValue) continue; if (state[di][dj]) count++; } if (state[i][j]) newState[i][j] = (count==2 || count==3); else newState[i][j] = (count==3); } } for (i=0;i