// hw.java
// This applet simulates a "passline" bet in craps (see Wikipedia for details)

// Written by Russ Woodroofe, 
//  modifying an applet of Julian Devlin, 8/97, for the text book
// "Introduction to Probability," by Charles M. Grinstead & J. Laurie Snell
// Licensed under the GNU General Public License, v2.0 or greater

// Packages we need
import java.awt.*;
import java.applet.Applet;
import java.util.Random;


public class hw1 extends Applet
{
	TextArea disp;		// Area to display random numbers
	
	Panel contp;		// Panel for user controls
	
	Label numl;			// Controls
	TextField num;
	Button go;
	
	Random randGen;		// Random number generator
	
	// Initialize applet
	public void init()
	{	
		numl = new Label("No.");			// Create controls
		num = new TextField("100", 4);
		go = new Button("Go");
		
		contp = new Panel();				// Set up control panel
		contp.add(numl);					
		contp.add(num);
		contp.add(go);
		contp.setLayout(new FlowLayout());
		
		disp = new TextArea(20, 30);		// Create display area
		
		resize(500,400);					// Set up applet
		setLayout(new FlowLayout());
		add(disp);
		add(contp);
		
		validate();
		
		randGen = new Random();			// Create random number generator
	}
	
	// Handle events
	public boolean handleEvent(Event evt)
	{
		if (evt.target instanceof Button)
		{
			if (evt.target == go && evt.id == Event.ACTION_EVENT)	
					// When button is clicked
			{
				disp.setText("");			// Reset output window
        		generate(Integer.valueOf(num.getText()).intValue());
        		return true;		// Generate correct number of random floats				
											
			}
		}
		return super.handleEvent(evt);	// Handle other events as usual
	}
	
	public void generate(int n)
	{
		int initial;
		int current;
		int successes=0;
		float percent;

		// Note: || means "or", != means "not equal", && means "and
		for(int i = 0; i < n; i++)
		{	
			// Note: randGen is type "Random", not type "JRandom"
			initial = 2 + randGen.nextInt(6) + randGen.nextInt(6);

			if (initial == 2 || initial == 3 || initial == 12)
				; // do nothing
			else if (initial == 7 || initial == 11)
				successes++;
			else
			{
				current=0;
				while (current != initial && current != 7)
					current = 2 + randGen.nextInt(6) + randGen.nextInt(6);

				if (current == initial)
					successes++;
			}
		}

		// Print results
		percent = ( (float) successes / (float) n) * 100;
		disp.appendText(Float.toString(percent));
		disp.appendText(" % wins.\n");
	}
	
}
