// P1203.java:$B%i%$%U%2!<%`(B

package applet;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import Glib.*;

public class P1203 extends xApplet
	implements Runnable,ActionListener
{	JButton[]bt=new JButton[3];
	String[]str={"Start","Reset","Exit"};
	Thread th=null;
	Image Im;
	xGraphics G,ImG;
	int N=20,r=7;
	int[][]f=new int[2*N+1][2*N+1];
	int[][]F=new int[2*N+1][2*N+1];

	public void init()
	{	app_init(7);
		Container cp=getContentPane();
		cp.setBackground(getBackground());
		cp.setLayout(new FlowLayout(FlowLayout.LEFT));
		for(int i=0;i<str.length;i++)
		{	bt[i]=new JButton(str[i]);
			bt[i].addActionListener(this);
			cp.add(bt[i]);
		}
		G=new xGraphics(getGraphics());
		G.set0(CA,0);
	}

	public void start(){}

	public void actionPerformed(ActionEvent evt)
	{	if(evt.getSource()==bt[0])
		{	if(th==null)
			{	th=new Thread(this);
				th.start();
			}
		}
		if(evt.getSource()==bt[1])
		{	th=null;
			repaint();
		}
		if(evt.getSource()==bt[2])
			System.exit(0);
	}

	public void stop()
	{	if(th!=null)
			th=null;
	}

	public void run()
	{	for(int y=0;y<=2*N;y++)
			for(int x=0;x<=2*N;x++)
				f[x][y]=xMath.fint(Math.random());
		G.rectangle(-r*(2*N+1)-1,-r*(2*N+1)-1,
			r*(2*N+1)+1,r*(2*N+1)+1,0);
	 	for(int y=0;y<=2*N;y++)
			for(int x=0;x<=2*N;x++)
				if(f[x][y]!=0)
					G.disk(2*r*(x-N),2*r*(y-N),r-1,0);
		Im=createImage(2*r*(2*N+1),2*r*(2*N+1));
		ImG=new xGraphics(Im.getGraphics());
		ImG.set0(r*(2*N+1),r*(2*N+1),0);
		Thread th0=Thread.currentThread();
		while(th==th0)
		{	try
			{	paint2();
				th.sleep(50);
			}
			catch(InterruptedException e){}
		}
	}

	private void paint2()
	{	for(int y=0;y<=2*N;y++)
			for(int x=0;x<=2*N;x++)
				F[x][y]=lifegame(x,y);
		ImG.frectangle(-r*(2*N+1),-r*(2*N+1),
			r*(2*N+1),r*(2*N+1),7);
		for(int y=0;y<=2*N;y++)
			for(int x=0;x<=2*N;x++)
				if(F[x][y]!=0)
					ImG.disk(2*r*(x-N),2*r*(y-N),r-1,0);
		G.putimage(Im,-r*(2*N+1),-r*(2*N+1),this);
		for(int y=0;y<=2*N;y++)
			for(int x=0;x<=2*N;x++)
				f[x][y]=F[x][y];
	}

	int lifegame(int x,int y)
	{	int s;
		{	if(y==0)
			{	if(x==0)
					s=			f[x+1][y]
					 +f[x][y+1]+f[x+1][y+1];
				else if(x==2*N)
					s=f[x-1][y]
					 +f[x-1][y+1]+f[x][y+1];
				else
					s=f[x-1][y]			   +f[x+1][y]
					 +f[x-1][y+1]+f[x][y+1]+f[x+1][y+1];
			}
			else if(y==2*N)
			{	if(x==0)
					s=f[x][y-1]+f[x+1][y-1]
							   +f[x+1][y];
				else if(x==2*N)
					s=f[x-1][y-1]+f[x][y-1]
					 +f[x-1][y];
				else
					s=f[x-1][y-1]+f[x][y-1]+f[x+1][y-1]
					 +f[x-1][y]			   +f[x+1][y];
			}
			else
			{	if(x==0)
					s=f[x][y-1]+f[x+1][y-1]
							   +f[x+1][y]
					 +f[x][y+1]+f[x+1][y+1];
				else if(x==2*N)
					s=f[x-1][y-1]+f[x][y-1]
					 +f[x-1][y]
					 +f[x-1][y+1]+f[x][y+1];
				else
					s=f[x-1][y-1]+f[x][y-1]+f[x+1][y-1]
					 +f[x-1][y]			   +f[x+1][y]
					 +f[x-1][y+1]+f[x][y+1]+f[x+1][y+1];
			}
		}
		if(s==2)
			return f[x][y];
		if(s==3)
			return 1;
		return 0;
	}
}
