import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CellularAutomataApplet extends Applet implements ActionListener
{
	private long[] bitboard = new long[32];
	private long[] matches  = new long[32];
	private long   pattern;

	private static final String REGEN_BOARD_CAPTION   = "Regenerate Board";
	private static final String REGEN_PATTERN_CAPTION = "Regenerate Pattern";

	public void randomiseBoard()
	{
		for(int i = 0; i < 32; i++)
		{
			this.bitboard[i] = (int)(Math.random() * Integer.MAX_VALUE);
			if(Math.random() >= 0.5)
				this.bitboard[i] |= 1 << 31;
		}
	}

	public void init()
	{
		this.randomiseBoard();
		this.randomisePattern();
		this.matchPatterns();
		this.createControls();
	}

	public void randomisePattern()
	{
		pattern = (int)(Math.random() * 16);
	}

	public void matchPatterns()
	{
		for(int i = 0; i < 32; i++)
		{
			this.matches[i] = 0;
		}

		for(int i = 0; i < 32; i++)
			for(int j = 0; j < 32; j++)
			{
				int fourBits = (int)((this.bitboard[i] >> j) & 15);

				if(pattern == fourBits)
				{
					this.matches[i] |= 15 << j;
				}
			}
	}

	public void paint(Graphics g)
	{
		// Draw board.
		int x = 0;
		int y = 0;
		int width = 8;
		int height = 8;
		for(int i = 0; i < 32; i++)
		{
			x = 1;
			for(int j = 0; j < 32; j++)
			{
				if((matches[i] & (1 << j)) != 0)
					g.setColor(Color.RED);
				else
					g.setColor(new Color(192, 192, 255));

				if((bitboard[i] & (1 << j)) != 0)
				{
					g.fillRect(x, y, width, height);
				}
				else
				{
					g.drawRect(x, y, width, height);
				}
				x += width;
			}
			y += height;
		}

		// Draw pattern to search for.
		g.setColor(Color.RED);
		for(int i = 0; i < 4; i++)
		{
			if((this.pattern & (1 << i)) != 0)
			{
				g.fillRect(8 + (width * i), y + 40, width, height);
			}
			else
			{
				g.drawRect(8 + (width * i), y + 40, width, height);
			}
		}
		g.setColor(Color.BLACK);
		g.drawString("Pattern to search for:", 8, y + 30);
	}

	public void actionPerformed(ActionEvent e)
	{
		if(e.getActionCommand().equals(CellularAutomataApplet.REGEN_BOARD_CAPTION))
		{
			this.randomiseBoard();
			this.matchPatterns();
			this.repaint();
		}
		else if(e.getActionCommand().equals(CellularAutomataApplet.REGEN_PATTERN_CAPTION))
		{
			this.randomisePattern();
			this.matchPatterns();
			this.repaint();
		}
	}

	private void createControls()
	{
		this.setLayout(new BorderLayout());
		Panel p = new Panel();
		Button b = new Button(CellularAutomataApplet.REGEN_BOARD_CAPTION);
		b.addActionListener(this);
		p.add(b);
		b = new Button(CellularAutomataApplet.REGEN_PATTERN_CAPTION);
		b.addActionListener(this);
		p.add(b);
		this.add(p, BorderLayout.PAGE_END);
	}
}
