I'm trying to create an applet in which the user gets a sheep into a pen by moving a dog towards the sheep and making the sheep move away from the dog in a random direction. The sheep and dog are defined as objects.
The applet is still in its very early stages. So far I can drag the dog object around the screen and when the dog object comes close to the sheep object it moves but only within a certain area (within bounds I have set). I'm not looking for the solution I'm just looking for some help.
What I would like help with is making the sheep object move in a random direction away from the dog when the dog object comes within the bounds I have set and not just move within the set bounds. Any help or tips would be greatly appreciated. Here is my code:
package mandAndDog;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class SheepDog extends Applet implements ActionListener, MouseListener, MouseMotionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
Dog dog;
Sheep sheep;
int xposR;
int yposR;
int sheepx;
int sheepy;
int sheepBoundsx;
int sheepBoundsy;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
dog = new Dog(10, 10);
sheep = new Sheep(200, 100);
sheepx = 175;
sheepy = 75;
sheepBoundsx = 50;
sheepBoundsy = 50;
}
public void paint(Graphics g)
{
dog.display(g);
sheep.display(g);
}
public void actionPerformed(ActionEvent ev)
{}
public void mousePressed(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseMoved(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{}
public void mouseDragged(MouseEvent e)
{
dog.setLocation(xposR, yposR);
if (xposR > sheepx&& xposR < sheepx+sheepBoundsx && yposR > sheepy
&& yposR < sheepy+sheepBoundsy){
sheep.setLocation(xposR + 50, yposR + 50);
}
xposR = e.getX();
yposR = e.getY();
repaint();
}
}
class Dog
{
int xpos;
int ypos;
int circleWidth = 30;
int circleHeight = 30;
public Dog(int x, int y)
{
xpos = x;
ypos = y;
}
public void setLocation(int lx, int ly)
{
xpos = lx;
ypos = ly;
}
public void display(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(xpos, ypos, circleWidth, circleHeight);
}
}
class Sheep
{
int xpos;
int ypos;
int circleWidth = 10;
int circleHeight = 10;
public Sheep(int x, int y)
{
xpos = x;
ypos = y;
}
public void setLocation(int lx, int ly)
{
xpos = lx;
ypos = ly;
}
public void display(Graphics g)
{
g.setColor(Color.green);
g.fillOval(xpos , ypos, circleWidth, circleHeight);
}
}