我正在尝试创建一个小程序,其中用户通过将狗移向羊并使羊沿随机方向远离狗来将羊放入笔中。羊和狗被定义为对象。
该小程序仍处于早期阶段。到目前为止,我可以在屏幕上拖动狗对象,当狗对象靠近绵羊对象时,它会移动,但只能在某个区域内(在我设置的范围内)。我不是在寻找解决方案,我只是在寻求帮助。
我想要帮助的是当狗对象进入我设定的范围内时,让绵羊对象在远离狗的随机方向上移动,而不仅仅是在设定的范围内移动。任何帮助或提示将不胜感激。这是我的代码:
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);
}
}