?? lifedemo.java
字號:
import java.applet.*;
import java.awt.*;
//定義一個LifeDemo類
public class LifeDemo extends Applet implements Runnable
{
static int col=30,row=10;
boolean life[][]=new boolean[col][row];
FontMetrics fm;
Thread m_thread=null;
//初始化
public void init()
{
resize(320,240);
Graphics g=getGraphics();
fm=g.getFontMetrics();
}
//paint()方法,實現同步
public synchronized void paint(Graphics g)
{
char chr[]=new char[1];
chr[0]='*';
for (int x=0;x<col;x++)
{
for(int y=0;y<row;y++)
{
if(life[x][y]==true)
{
g.setColor(getForeground());
g.drawChars(chr,0,1,x*fm.charWidth(chr[0]),y*fm.getHeight());
}
else
{
g.setColor(getBackground());
g.drawChars(chr,0,1,x*fm.charWidth(chr[0]),y*fm.getHeight());
}
}
}
}
//開始線程
public void start()
{
if (m_thread==null)
{
m_thread=new Thread(this);
m_thread.start();
}
}
//停止線程
public void stop()
{
if (m_thread!=null)
{
m_thread.stop();
m_thread=null;
}
}
//run()方法
public void run()
{
while(true)
{
try
{
Thread.sleep(500);
updateBoard();
repaint();
}
catch(InterruptedException e)
{
stop();
}
}
}
//負責更新數據
public synchronized void updateBoard()
{
int i;
Point p=new Point(0,0);
boolean iscurrentlife;
for (int x=0;x<col;x++)
{
for(int y=0;y<row;y++)
{
life[x][y]=false;
if (Math.random()>.76)
life[x][y]=true;
}
}
for (int x=0;x<col;x++)
{
for(int y=0;y<row;y++)
{
iscurrentlife=life[x][y];
int islife=0;
if (y>0)
{
p.y=y-1;
for ( i=-1;i<=1;i++)
{
if ((x+i)<0) continue;
if ((x+i)==col) continue;
p.x=x+i;
if (life[p.x][p.y]==true)
islife++;
}
}
if (y<(row-1))
{
p.y=y+1;
for (i=-1;i<=1;i++)
{
if ((x+i)<0) continue;
if ((x+i)==col) continue;
p.x=x+i;
if (life[p.x][p.y]==true)
islife++;
}
}
for (i=-1;i<=1;i++)
{
if ((x+i)<0) continue;
if ((x+i)==col) continue;
p.x=x+i;
p.y=y;
if (life[p.x][p.y]==true)
islife++;
}
if (iscurrentlife)
{
if (islife<2) life[x][y]=false;
if (islife>3) life[x][y]=false;
}
else
{
if (islife==3) life[x][y]=true;
}
}
}
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -