📄 wolf.java
字号:
package com.lovo.pig.model;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Random;
import com.lovo.pig.view.MainFrame;
public class Wolf{
private MainFrame mf;
private Random rand = new Random();
//狼起飞位置
public int flyX;
//狼的位置
public int x = 5,y = 480;
//狼图像下标
private int indexImg = 0;
//狼被击中图像下标
private int indexHittedImg = 0;
//狼生命值
public int hp = 3;
//狼存活状态
public boolean live = true;
//狼图像切换延迟,可减轻闪烁
private int delay = 0;
//狼被击中与否
public boolean hitted = true;
//击中狼的子弹的坐标
public int bulletX,bulletY;
//吹气球延迟
private int delayBalloon = 5;
public Wolf(MainFrame mf) {
this.mf = mf;
//计算起飞位置,起飞位置必须是5的倍数
//当然也可以改成其他数的倍数,但这里改了,气球的相关参数也要改
this.flyX=rand.nextInt(100)*5 + 5;
}
/**
* 绘制狼图像
* @param g
*/
public void draw(Graphics g) {
//绘制狼本身
g.drawImage(mf.images.getImgWolves()[indexImg],x,y,null);
if(hitted && hp >0){//绘制被子弹击中的图像
g.drawImage(mf.images.getImgHitWolf()[indexHittedImg],bulletX - 5,bulletY - 10,null);
indexHittedImg ++;
if(indexHittedImg > 2){
indexHittedImg = 0;
hitted = false;
}
}
move();
}
/**
* 改变狼图像下标和位置
*/
public void move() {
//生命值耗尽,挂
if(hp == 0){
live = false;
}
if(live){ //存活时
if(x<flyX){//起飞前,反复使用前四张前进图像
indexImg++;
x=x+5;
if(indexImg>3){
indexImg=0;
}
}else if(x == flyX){//狼起飞,使用第一张图像
indexImg= 0;
if(delayBalloon == 0){
x=x+1;
}
delayBalloon--;
}else if(x>flyX && y>18){//狼上升,反复使用第五/六张图像
if(indexImg == 0){
indexImg=4;
}
if(delay == 0){//这里使用延迟,避免频繁切换图像,造成闪烁
delay = 4;
indexImg++;
}
if(indexImg>5){
indexImg=4;
}
y=y-6;
delay--;
}else if(y<= 18 && x<650){//狼停止上升,前进,,反复使用前四张前进图像
indexImg++;
if(indexImg>=3){
indexImg=0;
}
x=x+6;
}else if(x >= 650){//狼前进到轮子旁,使用切割绳子的图像
indexImg++;
//播放狼剪断绳子音乐
mf.musics.cut();
if(indexImg < 11 || indexImg>12){
indexImg=11;
}
mf.currentPig.live=false;
}
} else if(!live){//狼挂时,反复使用下掉的图像
indexImg++;
if(indexImg<6||indexImg>11){
indexImg=6;
}
y=y+20;
if(y > 600){//越界时清除狼对象
mf.wolves.remove(this);
}
}
}
/**
* 返回狼边界矩形,用于碰撞检测
* @return
*/
public Rectangle getRect(){
Rectangle rect = new Rectangle(x,y,
mf.images.getImgWolves()[indexImg].getWidth(null) - 60,
mf.images.getImgWolves()[indexImg].getHeight(null) - 20
);
return rect;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -