// Darts.java

// Written by Julian Devlin, 8/97, for the text book
// "Introduction to Probability," by Charles M. Grinstead & J. Laurie Snell

import java.applet.Applet;
import java.awt.*;

public class Darts extends java.applet.Applet
{
	Float[] yCoords;		// Variables for simulation - on unit circle
	Float[] xCoords;
	
	Float[] abgX;
	Float[] abgY;
	
	AreaBarGraph abg;				// AWT elements
	DartBoard db;
	Label message;
	Button go;
	TextField num;
		
	Panel graphArea;
	Panel controls;
	
	JRandom myRand;

	// Set up all controls and put them in the window
	public void init() {
		message = new Label("Number of darts =");	// Create controls
		go = new Button("Simulate");
		num = new TextField(4);
		
		graphArea = new Panel();				// Set up window
		controls = new Panel();
		setLayout(new BorderLayout(5, 5));
	
		controls.setLayout(new FlowLayout());
		controls.add(message);
		controls.add(num);
		controls.add(go);
		
		abg = new AreaBarGraph(); // initialize a graphing space
		db = new DartBoard();
		add("Center", graphArea);
		graphArea.setLayout(new GridLayout(2, 1));
		graphArea.add(abg);
		graphArea.add(db);
		add("South", controls);
		
		myRand = new JRandom();
	}
	
	
	// Does the simulation, creating two arrays to store game states, then passes them
	// to a AreaBarGraph
	public void simulate() {
		int n = 0;
		try {
			n = Integer.parseInt(num.getText().trim());		// Get user input
		}
		catch (Exception e) {
			num.setText("");
			validate();
		}
		xCoords = new Float[n + 1];					// Make arrays
		yCoords = new Float[n + 1];
		
		abgX = new Float[11];
		abgY = new Float[11];
		int[] tempY = new int[11];
		
		for (int i = 0; i < 11; i++) {
			abgX[i] = new Float(i * .1);
			tempY[i] = 0;
		}
		
		int index;
		
		for (int i = 0; i < n + 1; i++) {				// Do actual simulation
			do {
				xCoords[i] = new Float(myRand.nextFloat(-1, 1));
				yCoords[i] = new Float(myRand.nextFloat(-1, 1));
			} while (Math.pow(xCoords[i].floatValue(), 2f) 
				+ Math.pow(yCoords[i].floatValue(), 2f) > 1);
			
			index = (int) Math.ceil(Math.pow(Math.pow(xCoords[i].floatValue(), 
				2f) + Math.pow(yCoords[i].floatValue(), 2f), .5) * 10);
			tempY[index]++;
		}
		
		for (int i = 0; i < 11; i++) {
			abgY[i] = new Float(((float) tempY[i] / (float) n) / .1);
		}
		
		message.setText("Number of darts =");
		graphArea.remove(abg);
		graphArea.remove(db);
		abg = new AreaBarGraph(abgX, abgY);	// Create new AreaBarGraph
		db = new DartBoard(xCoords, yCoords);
		graphArea.add(abg);
		graphArea.add(db);							
		validate();
	}
	
	// Watch for a click on the go button
	public boolean action(Event evt, Object arg) {
		if (evt.target instanceof Button) {
			if ((String)arg == "Simulate") {
				simulate();
			}
		}
		return true;
	}
	
	public Insets insets() {
    	return new Insets(5,5,5,5);
	}
}