鲨鱼攻击猎物游戏
是一个Applet程序
源代码在线查看: sharkprey.java
package shark;
import java.awt.*;
/**
* 猎物类,实现猎物的显示、移动、以及判断是否被鲨鱼吃掉等功能
*/
public class SharkPrey {
private SharkAttack applet = null;
private Image animal = null; //猎物的图片
private Rectangle bounds = new Rectangle();
private int deltaX, amp; //位移和振幅
public SharkPrey(Image _animal, SharkAttack _applet) {
animal = _animal;
applet = _applet;
deltaX = (int) (2 * Math.random()) + 1;
amp = (int) (55 * Math.random()) + 10;
bounds.x = (int) (applet.getSize().width * Math.random());
bounds.y = 120 + (int) (amp * Math.sin(bounds.x / 20.0));
bounds.height = animal.getHeight(null);
bounds.width = animal.getWidth(null);
}
/**
* 猎物的移动路线是简单的正弦曲线(振幅是随机的),初始位置随机产生。
*/
public void move() {
if ((bounds.x > applet.getSize().width) || (bounds.x < 0)) {
deltaX *= (-1);
}
bounds.x += deltaX;
bounds.y = 120 + (int) (amp * Math.sin(bounds.x / 20.0));
}
/**
* @param shark
* @return 如果获得的鲨鱼鱼鳍顶点坐标值在猎物所在的矩形区域内,则猎物被吃掉,返回值为true,否则为false
*/
public boolean isEatenBy(Shark shark) {
return bounds.contains(shark.getTip());
}
public void paintComponent(Graphics g) {
g.drawImage(animal, bounds.x, bounds.y, null);
}
}