// Craps.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 Craps
	extends java.applet.Applet
{
	TextArea disp;		// Area to display HT
	
	Panel dispArea;
	Panel controls;		// Panel for user controls
	
	Label numl;			// Controls
	TextField num;
	Button go;
	
	GridBagLayout gbl;
	GridBagConstraints cc;
	
	JRandom myRand;
		
	// Initialize applet
	public void init()
	{	
		numl = new Label("n =");			// Create controls
		num = new TextField("100", 4);
		
		go = new Button("Go");
		
		disp = new TextArea(15, 20);		// Create display area
		
		dispArea = new Panel();				// Set up window
		controls = new Panel();
		setLayout(new BorderLayout(5, 5));
		
		add("South", controls);
		add("Center", dispArea);
		
		dispArea.setLayout(new GridLayout(1, 1));
		dispArea.add(disp);
		
		gbl = new GridBagLayout();
		controls.setLayout(gbl);
		
		cc = new GridBagConstraints();
		
		cc.gridx = 0;
		cc.gridy = 0;
		gbl.setConstraints(numl, cc);
		controls.add(numl);
		
		cc.gridx = 1;
		gbl.setConstraints(num, cc);
		controls.add(num);
		
		cc.gridx = 0;
		cc.gridy = 1;
		cc.gridwidth = 2;
		gbl.setConstraints(go, cc);
		controls.add(go);
		
		validate();
		
		myRand = new JRandom();
	}
	
	// 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
        		simulate(Integer.valueOf(num.getText()).intValue());
        		return true;					// Generate correct number of tosses
			}
		}
		return super.handleEvent(evt);	// Handle other events as usual
	}
	
	public int roll() {
		return myRand.nextInt(1, 6) + myRand.nextInt(1, 6);
	}
	
	// Calculate probabilities
    public void simulate(int num)
    {	
    	int wins = 0;
    	int temp, temp2;
    
    	for (int i = 0; i < num; i++) {
	    	temp = roll();
	    	if (temp == 7 || temp == 11)
	    		wins++;
	    	else if (temp == 2 || temp == 3 || temp == 12)
	    		;
	    	else {
	    		do {
	    			temp2 = roll();
	    		} while (temp2 != temp && temp2 != 7);
	    		if (temp2 == temp)
	    			wins++;
	    	}
		}
    
    	disp.appendText("Average wining is  " + 
    		String.valueOf((float) wins / (float) num) + "\n");
    }

}