⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 lifedemo.java

📁 面向对象技术
💻 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 + -