菜鸟日记—2月10日
案例 : 飞机大战
要求: 玩家可控制飞机躲避炮弹,界面显示玩家游玩时间
效果:
1.游戏物体根类
(飞机,炮弹等类都继承于此类)
import java.awt.*;
/*
* 游戏物体的根类
* */
public class GameObject {
Image img; //图片
double x,y; //物体的坐标
int speed; //物体移动的速度
int width,height; //物体的宽度和高度
public GameObject(Image img, double x, double y, int speed, int width, int height) {
this.img = img;
this.x = x;
this.y = y;
this.speed = speed;
this.width = width;
this.height = height;
}
public GameObject(Image img, double x, double y, int speed) {
this.img = img;
this.x = x;
this.y = y;
this.speed = speed;
this.width = img.getWidth(null);
this.height = img.getHeight(null);
}
public GameObject(){
}
public void drawMyself(Graphics g){
g.drawImage(img,(int)x,(int)y,width,height,null);
}
//碰撞检测器
//所有的物体都是矩形。当你获得对应的矩形的时候,我们就可以做一些相关的判断的操作!
public Rectangle getRec(){
return new Rectangle((int)x,(int)y,width,height);
}
}
2.飞机类
import java.awt.*;
import java.awt.event.KeyEvent;
/*
* 飞机相关属性类
* */
public class Plane extends GameObject{
//移动方向
boolean up,down,left,right;
boolean live = true; //活着
@Override
public void drawMyself(Graphics g){
//飞机飞行的算法,可自行设定
//x += speed;
//死了就不绘制飞机
if (live){
super.drawMyself(g);
if (up){
y -= speed;
}
if (down){
y += speed;
}
if (left){
x -= speed;
}
if (right){
x += speed;
}
if (x >= 770){
x = 760;
}
if (x <= 0){
x = 10;
}
if (y