// File: Race1.java (Module 12) // // Author: Rahul Simha // Created: Nov 17, 1998 // // A simple simulation without threads. import java.awt.*; import java.awt.event.*; class NewFrame extends Frame { Canvas c; public NewFrame () { // Frame properties. this.setTitle ("Dog Race"); this.setBackground (Color.cyan); this.setResizable (true); this.setSize (600,200); // Quit button. Panel p = new Panel (); Button quitb = new Button ("QUIT"); quitb.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { System.exit (0); } } ); p.add (quitb); // Pressing "start" calls race() Button startb = new Button ("START"); startb.addActionListener ( new ActionListener () { public void actionPerformed (ActionEvent a) { race (); } } ); p.add (startb); this.add (p, BorderLayout.SOUTH); // A canvas to draw the results. c = new Canvas(); c.setBackground (Color.white); this.add (c, BorderLayout.CENTER); this.setVisible (true); } void race () { Dimension D = c.getSize (); // Finish-line is at the right end of the canvas. int finish_line = D.width; // Create two dog instances with different ID's. Dog d1 = new Dog (1, c); Dog d2 = new Dog (2, c); // Each dog sleeps a random amount of time. int d1_nextwakeup = (int) UniformRandom.uniform (300,600); int d2_nextwakeup = (int) UniformRandom.uniform (300,600); // Keep track of the current time. int current_time = 0; // Stop when one dog crosses the finish line. while ( (d1.position < finish_line) && (d2.position < finish_line) ) { // See which one is done first. if (d1_nextwakeup < d2_nextwakeup) { try { // Static method "sleep" in class Thread. Thread.sleep (d1_nextwakeup - current_time); } catch (InterruptedException e) { System.out.println (e); } current_time = d1_nextwakeup; d1.move(); // Move a random distance. d1_nextwakeup += (int) UniformRandom.uniform (300,600); } else { try { Thread.sleep (d2_nextwakeup - current_time); } catch (InterruptedException e) { System.out.println (e); } current_time = d2_nextwakeup; d2.move(); // Move a random distance. d2_nextwakeup += (int) UniformRandom.uniform (300,600); } } } } class Dog { public int position = 20; // Starting position. int ID; // An ID. Canvas c; // The canvas on which to draw. public Dog (int ID, Canvas c) { this.ID = ID; this.c = c; // Draw ID on canvas. Graphics g = c.getGraphics (); g.drawString (""+ID, 5, 20*ID+8); } public void move () { // Move a random amount. int new_position = position + (int) UniformRandom.uniform (50,100); // Draw new position. Graphics g = c.getGraphics (); int size = new_position - position; g.fillRect (position, 20*ID, size, 10); position = new_position; } } public class Race1 { public static void main (String[] argv) { NewFrame nf = new NewFrame (); } }