import objectdraw.*; import java.awt.*; public class CoinFlipSimulator extends WindowController { private static final int heads = 1; // These are constants. private static final int tails = 2; // The value is final // and it cannot change // or vary like a variable's can. private FilledOval coin; private Text coinFace; private int headsCount; private int tailsCount; private int missdCount; private Text headsReport, tailsReport, missdReport; private Location headsTailsLocation; private RandomIntGenerator generator; // has to be declared out here // as an instance variable. Why? public void begin() { headsCount = 0; tailsCount = 0; missdCount = 0; coin = new FilledOval(75, 100, 100, 100, canvas); coin.setColor( new Color(255, 204, 0 ) ); new FramedOval(75, 100, 100, 100, canvas); coinFace = new Text("Click to Flip", 93, 143, canvas); coinFace.setBold(); headsTailsLocation = new Location( 107, 143 ); headsReport = new Text("Heads: 0", 125, 220, canvas); tailsReport = new Text("Tails: 0", 125, 240, canvas); missdReport = new Text("Missed: 0", 125, 260, canvas); missdReport.setColor( Color.red ); generator = new RandomIntGenerator(1, 2); // Create the random // generator that only // does 2 values, 1 and 2. } public void onMousePress(Location point) { int flipValue; // local integer variable for // holding the result of the // coin flip, Heads or Tails, 1 or 2 String coinMessage; // local String object variable. if ( coin.contains(point) ) { flipValue = generator.nextValue(); // Generates a random // integer 1 (H) or 2 (T). if (flipValue == heads) { coinMessage = "Heads"; headsCount = headsCount + 1; headsReport.setText( "Heads: " + headsCount ); } else // if (flipValue == tails) { coinMessage = "Tails"; tailsCount = tailsCount + 1; tailsReport.setText( "Tails: " + tailsCount ); } coinFace.moveTo( headsTailsLocation ); coinFace.setText( coinMessage ); } else { missdCount = missdCount + 1; missdReport.setText("Missed: " + missdCount); } } }
Now that you have added to code to display the BLUE rectangle with its "Reset Counts" message, add the Java code so that a Click event (or an onMousePress() event, if you prefer), would cause the Heads and Tails and Missed messages and the corresponding int counter variables to all be reset to or display 0?
Check it out: See the Java Applet and try it out. It has all the above features, plus some surprising extras.