// DeMere2.java
// This applet rolls a pair of dice in sets of 24 or 25, seeing if a 
// pair of sixes comes up in each set.

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

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


public class DeMere2 extends Applet
{
	TextArea disp;		// Area to display percentage
	
	Panel contp;		// Panel for user controls
	
	Label numl;			// Controls
	TextField num;
	Button go24;
	Button go25;
	
	JRandom randGen;		// Random number generator
	
	// Initialize applet
	public void init()
	{	
		numl = new Label("No. of games");			// Create controls
		num = new TextField("30", 4);
		go24 = new Button("24 times");
		go25 = new Button("25 times");
		
		contp = new Panel();				// Set up control panel
		contp.add(numl);					
		contp.add(num);
		contp.add(go24);
		contp.add(go25);
		contp.setLayout(new FlowLayout());
		
		disp = new TextArea(10, 30);		// Create display area
		
		setLayout(new FlowLayout());
		add(disp);
		add(contp);
		
		validate();
		
		randGen = new JRandom();			// Create random number generator
	}
	
	// Handle events
	public boolean handleEvent(Event evt)
	{
		if (evt.target instanceof Button)
		{
			if (evt.target == go24 && evt.id == Event.ACTION_EVENT)	// When go24 is clicked
			{
				disp.setText("");			// Reset output window
        		generate(Integer.valueOf(num.getText()).intValue(), 24);
        		return true;					// Generate correct number of games
			}
			else if (evt.target == go25 && evt.id == Event.ACTION_EVENT)// When go25 is clicked
			{
				disp.setText("");			// Reset output window
        		generate(Integer.valueOf(num.getText()).intValue(), 25);
        		return true;					// Generate correct number of games
			}
		}
		return super.handleEvent(evt);	// Handle other events as usual
	}
	
	// Generate n sets of set dice pairs, and print average wins (you get a pair of sixes)
    public void generate(int n, int sets)
    {
    	int count = 0;
    	int randInt1, randInt2;
    	float percent;
    	for(int i = 0; i < n; i++)		// Num games
    	{
    		for(int j = 0; j < sets; j++)	// Usually 24 or 25
    		{
    			randInt1 = randGen.nextInt(6);
    			randInt2 = randGen.nextInt(6);
    			if (randInt1 == 6 && randInt2 == 6)
    			{	
    				count++;				// Double sixes
    				j = sets;
    			}
    		}
    	}
    	percent = ((float) count/ (float) n) * 100;	// Print
    	disp.appendText(Float.toString(percent));
    	disp.appendText("% win rate.");
	}
	
	
}
