Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Thread - Hare and Tortoise Program

807605Jul 1 2007 — edited Jul 1 2007
Hello, newbie here...

I'm writing this program but when I click the start button which should initiate either the Hare or the Tortoise, it does not, this is the first time I use threads, so the problem might be the way I'm passing the value.

can someone please take a look at this code and maybe give me some guidance on what I'm doing wrong.

Please note there are 3 separate files with the corresponding classes, I separated it with ===>
Thank You
JC
package turtoiseandhare;

import java.awt.*;
import java.*;
import javax.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.accessibility.*;
import java.util.*;
import java.awt.event.*;

public class TurtoiseAndHare extends JFrame
{
    private ImageIcon hare;
    private ImageIcon tortoise;

    private ImageIcon start;
    private ImageIcon finish;
    int turtle_x = 0;
    int turtle_y = 159;
    int hare_x = 0;
    int hare_y = 35;
    int ha_w;
    int ha_h;
    int to_w;
    int to_h;
    float fastplod;
    float slip;
    float slowplod;

    float sleep;
    float bighop;
    float bigslip;
    float smallhop;
    float smallslip;

    Display p;
    Move mo;
    TnHThread tornhare;
    Button StartB;
    Button Stop;
    String message = "Who will win this amazing race!";

    public TurtoiseAndHare()
    {
        setTitle ("Tortoise and the Hare race!");
        setSize(1000, 405);
        mo = new Move(this);

        Container contentPane = this.getContentPane();
        getContentPane().setLayout(new BorderLayout());

        p = new Display();

        
        JPanel q = new JPanel();
        q.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        StartB = new Button("  Start  ");
        q.add(StartB);

        JPanel m = new JPanel();
        m.setBorder(BorderFactory.createLineBorder(Color.BLUE));
        m.setBackground(Color.getHSBColor(25,55,45));
        JLabel msg = new JLabel(message);
        m.add(msg);

        hare = new ImageIcon(getClass().getResource("hare.jpg"));
        tortoise = new ImageIcon(getClass().getResource("Turtle.jpg"));
        start = new ImageIcon(getClass().getResource("start.jpg"));
        finish = new ImageIcon(getClass().getResource("finish.jpg"));

        contentPane.add(p, BorderLayout.CENTER);
        contentPane.add(q, BorderLayout.SOUTH);
        contentPane.add(m, BorderLayout.NORTH);

        Handler handler = new Handler();
        StartB.addActionListener(handler);
    }
    class Display extends Canvas
    {
        public void paint(Graphics  g)
        {
            ha_w = hare.getIconWidth();
            ha_h = hare.getIconHeight();
            to_w = tortoise.getIconWidth();
            to_h = tortoise.getIconHeight();

           // super.paint(g);
           for (int i = 0; i < 780; i++)
           {
               tortoise.paintIcon(p, g, i+5, turtle_y);
  
           };
            tortoise.paintIcon(p, g, turtle_x, turtle_y);
            hare.paintIcon(p, g, hare_x, hare_y);
            start.paintIcon(p, g, 125, 0);
            finish.paintIcon(p, g, 850, 0);

            g.drawString(message,170,55);
        }
    } //end of Display
    public void raicing(int animal, int x, int y)
    {
        if (animal == 1)
        {
            hare_x = x;
            hare_y = y;
            message = "the hare is at position " + hare_x;
        }
        if (animal == 2)
        {
            turtle_x = x;
            turtle_y = y;
            message = "The Turtoise is at position " + turtle_x;
        }
        p.repaint();
    }//END of Raicing
    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub
        TurtoiseAndHare myrace = new TurtoiseAndHare();
        myrace.setVisible(true);
  myrace.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }//END of Main

    class Handler implements ActionListener
    {
        public void actionPerformed (ActionEvent e)
        {
            int send;
            Random startNo = new Random();
            send = 1 + startNo.nextInt(2);
            //start button was pressed
            if (send == 1)
            {
                TnHThread h = new TnHThread(send,mo);
                h.start();
            }
            else if (send == 2)
            {
                TnHThread t = new TnHThread(send,mo);
                t.start();
            }
        }
    }
}

==================================>
MOVE class

package Tortoiseandhare;

import java.util.Random;

public class Move {
 
  private boolean lock = true; //1st

  TortoiseAndHare frame;

  public Move(TortoiseAndHare fr) {frame = fr;}

  public void moving(int animal, int hare_x, int hare_y)
  {
      if (animal == 1)moving_hare(animal, hare_x, hare_y);
      if (animal == 2)moving_Tortoise(animal, hare_x, hare_y);
  }//End of moving
  public void moving_hare(int animal, int hare_x, int hare_y)
  {
      hare_start();
      go(animal, hare_x, hare_y);
      hare_stop();
  }//End of Moving_hare
  public synchronized void hare_start()
  {
      while (lock == false)
      {
          try
          {
              wait();
          }
          catch (InterruptedException e)
          {
              System.out.println("Interrupted Exception on the hare");
          }
      }//End Of while
      lock = false;
      notifyAll();
  }//END of Synch hare_start

  public synchronized void hare_stop()
  {
      lock = true; //3rd
      notifyAll();
  }//END of hare_stop

  public void moving_Tortoise(int animal, int hare_x, int hare_y)
  {
      Tortoise_start();
      go(animal, hare_x, hare_y);
      Tortoise_stop();
  }//end of Tortoise_start
  public synchronized void Tortoise_start()
  {
      while (lock == false) //7th
      {
          try
          {
              wait();
          }
          catch(InterruptedException e)
          {
              System.out.println("Interrupted Exception on the Tortoise");
          }
      }//END of While
          lock = false; //4th
          notifyAll();
      }   //End of Synch Tortoise_start

      public synchronized void Tortoise_stop()
      {
          lock = true; //5th
          notifyAll();
      }
      public void go(int animal, int hare_x, int hare_y)
      {
          if (animal == 1) //if animal == hare
          {
              hare_y = 35;
              
              float RandomNo;
              Random RandNumber = new Random();
              RandomNo = RandNumber.nextFloat(); 
                
              if ( (RandomNo > 0) && (RandomNo <= 0.2) ) //Sleep
              {
                  //No Move at all
                  try{Thread.sleep(1000);}
                  catch(Exception e){System.err.println("Exception at the Sleeping Thread");}
                  
                   System.out.println("moving number from Move.go. animal 1  " + animal+ " x = "+hare_x+" y is "+hare_y);
              }
              else if ( (RandomNo > 0.2) && (RandomNo <= 0.4 ) ) //Big Hop
              {
                  System.out.println(" Hare (RandomNo > 0.2) && (RandomNo <= 0.4 ) ");
                  //7 Position to the right
                  hare_x = hare_x + 7;
                  frame.setLocation(hare_x, hare_y);
                  try{Thread.sleep(100);}
                  catch(Exception e){System.err.println("Exception at the Sleeping Thread");}
                  
              }
              else if ( (RandomNo > 0.4) && (RandomNo <= 0.5) ) //Big slip
              {
                  //10 Position to the left
                  hare_x = hare_x - 10;
                  frame.setLocation(hare_x, hare_y);
                  try{Thread.sleep(100);}
                  catch(Exception e){System.err.println("Exception at the Sleeping Thread");}
                  
              }
              else if ( (RandomNo > 0.5) && (RandomNo <= 0.8) ) //Small hop
              {
                  //1 position to the right
                  hare_x = hare_x + 1;
                  frame.setLocation(hare_x, hare_y);
                  try{Thread.sleep(100);}
                  catch(Exception e){System.err.println("Exception at the Sleeping Thread");}
              }
              else if ( (RandomNo > 0.8) && (RandomNo <= 1.0) ) //small Slip
              {
                  //2 position to the left
                  hare_x = hare_x - 2;
                  frame.setLocation(hare_x, hare_y);
                  try{Thread.sleep(100);}
                  catch(Exception e){System.err.println("Exception at the Sleeping Thread");}
                                }
              if (hare_x > 770)
              {
                  System.out.println("The Hare Wins the Race");
              }

          }
          if (animal == 2) //if animal == Tortoise
{
  hare_y = 159;
  float RandomNo;
  Random RandNumber = new Random();
Math.abs(RandomNo = RandNumber.nextFloat()); 


  RandomNo = RandNumber.nextFloat();
  if ( (RandomNo > 0) && (RandomNo <= .5) ) //Fast Plod Right
  {
      //2 Position to the Right
      hare_x = hare_x + 2;
      frame.setLocation(hare_x, hare_y);
      try{Thread.sleep(100);}
                  catch(Exception e){System.err.println("Exception at the Sleeping Thread");}
  }
  else if ( (RandomNo > .5) && (RandomNo <= .7) ) //Slip left
  {
      //Slip 4 Position to the left
      hare_x = hare_x - 4;
      frame.setLocation(hare_x, hare_y);
      try{Thread.sleep(100);}
                  catch(Exception e){System.err.println("Exception at the Sleeping Thread");}
  }
  else if( (RandomNo > .7) && (RandomNo <= 1)) //Slow Plod Right
  {
      //1 Position to the right
      hare_x = hare_x + 1;
      frame.setLocation(hare_x, hare_y);
      try{Thread.sleep(100);}
                  catch(Exception e){System.err.println("Exception at the Sleeping Thread");}
  }
  if (hare_x > 770)
  {
   System.out.println("The Tortoise Wins the Race");
   try{Thread.sleep(100);}
                  catch(Exception e){System.err.println("Exception at the Sleeping Thread");}
  }
}
      }//END of go
}//End of Class Move


==================>
THREAD CLASS

package turtoiseandhare;

import java.util.Random;
public class TnHThread extends Thread
{
    public int animal;
    private int x;
    private int y;

    Move m;
    
    public TnHThread(int tr, Move m1)
      {
      animal = tr;

        m = m1;
        if (animal == 1){x = 0; y = 35;}
        if (animal == 2){x = 0; y = 158;}
    }

    public void run()
    {
        m.moving(animal, x, y);
    }
}


====================>
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 29 2007
Added on Jul 1 2007
2 comments
753 views