import java.lang.*;
import java.awt.*;
import java.applet.*;



public class GeneticApplet extends Applet implements Runnable
{
	public  Thread      thread;

	public	int         ROWS;
	public	int         COLUMNS;
	public  int         SPEED;

	public  Board	    board;
	public  Knight	    knight;
    public  Image       KnightImage;



	public void init()
	{
        ROWS        = Integer.parseInt(getParameter("DIMENSION"));
		COLUMNS     = Integer.parseInt(getParameter("DIMENSION"));
        SPEED       = Integer.parseInt(getParameter("SPEED"));

		setFont(new Font("TimesRoman",Font.BOLD,  ((size().width/ROWS)*8/10)));
		board = new Board(size().width, size().height, ROWS, COLUMNS, new Color(216, 255, 255), new Color(216, 216, 216));
    	KnightImage = getImage(getCodeBase(), "images/knight.gif");
	}


    // Entering the Applet. Start the thread...
	public void start()
	{
	    board.Clear();
		if (thread==null)
		{
			thread=new Thread(this);
			thread.setPriority(Thread.NORM_PRIORITY);
			thread.start();
		}
	}


    // Run the thread.
    public void run()
    {
        while (true)
        {
            //
            // main loop
            //

            synchronized(this)
            {
                if (knight != null)
                {
                    if(knight.path.Full())
                    {
                        stop();
                    }
                    else
                    {
                        // showStatus(knight.GA.ThePopulation.Progress());
                    }

                }
            }

            // Sleep for sometime...
            try
            {
                if (SPEED != 0)
                {
                    thread.sleep(1000 / SPEED);
                }
            }
            catch (InterruptedException e) { }


        }
    }


    // Leaving the Applet. Stop the thread...
	public void stop()
	{
	    if (thread != null)
	    {
            board.Draw(getGraphics());

            thread.stop();
            try
            {
                thread.join();
            }
            catch (InterruptedException e) { }
        }
        thread = null;
	}




	public synchronized void paint(Graphics _g)
	{
		board.Draw(_g);
    }




	public boolean mouseDown(Event evt, int x, int y)
	{
        if (knight == null)
        {
            Position start = new Position((x/(board.width() /board.rows())), (y/(board.height()/board.columns())));
      		knight = new Knight(3, Color.white, KnightImage, board, start, SPEED);
            knight.FindPath(this);
        }
   		return true;
	}




	public String getAppletInfo()
	{
		return "aliadams@bournemouth.ac.uk 1997";
	}


}
