import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
//requires Horse and HorseRun2, run it in HorseRun2
public class HorseRace extends JComponent implements Runnable
{
    horse competitors [];
    boolean stopped = false; //a variable that is true when a horse wins
    boolean endit = false; //a variable that is changed by the reset method
    Applet surface;
    // 13 predefined colors
    Color colors [] = {Color.red, Color.blue, Color.cyan, Color.darkGray, Color.gray, Color.green, Color.lightGray, Color.magenta, Color.orange, Color.pink, Color.red, Color.white, Color.yellow};
    String names [] = {"Mr. Ed", "Bob", "Mike", "Rawr", "Horse", "Juno", "Io", "Crovax", "Crash", "Loser", "Pop", "Kalor", "Krundor", "Werehorse"};
    int numHorses = 12;

    
    public HorseRace (int num, Applet surface2)
    { //set up horseface
	setDoubleBuffered (true);
	numHorses = num;
	surface = surface2;
	competitors = new horse [num];
	int calc = (int) (300 / num);
	int y = 65;
	for (int i = 0 ; i < num ; i++)
	{
	    competitors [i] = new horse (surface, colors [i], names [i]);
	    competitors [i].startHorse (30, y);
	    competitors [i].drawHorse ();
	    y += calc;
	}
    }


    public synchronized void run ()
    {
	stopped = false; //a variable that is true when a horse wins
	endit = false; //a variable that is changed by the reset method

	while (!stopped && !endit) //while no one has won and the user isn't bored
	{
	    for (int i = 0 ; i < numHorses ; i++)
	    {
		if (competitors [i].checkit ())
		{
		    stopped = competitors [i].checkit ();
		    JOptionPane.showMessageDialog (null, competitors [i].getName () + " has won!", "We have a winner!", JOptionPane.INFORMATION_MESSAGE);
		}
		if (!stopped)
		{
		    //erase the horses
		    competitors [i].eraseHorse ();
		    //move the horses
		    competitors [i].moveHorse ();
		}
		//draw the horses in their new place
		competitors [i].drawHorse ();
	    }
	    //sleep for a bit
	    try
	    {
		Thread.sleep (5);
	    }
	    catch (InterruptedException x)
	    {
		;
	    }
	}
    }


    public void reset ()
    {
	endit = true; //user is bored, stop the run loop
	int calc = (int) ((surface.getSize ().getHeight () - 100) / numHorses);
	int y = 65;
	for (int i = 0 ; i < numHorses ; i++)
	{
	    //erase the horses
	    competitors [i].eraseHorse ();
	    //reset the horse positions
	    competitors [i].startHorse (30, y);
	    //draw the two horses
	    competitors [i].drawHorse ();
	    y += calc;
	}
    }
    
    public void paint (Graphics g)
    {
	g.clearRect (0,0, 700, 400);
    }
}
