飞机大战
一周前开始学习java基础,看了尚学堂高老师的视频,跟着做了一个飞机大战游戏的小项目,现在整理总结一下。
问题分析
模拟游戏,飞机可以由上下左右方向键控制,飞机被限制在window边界内,不能越过边界。炮弹碰到飞机,飞机死亡爆炸。
飞机大战中所需要的对象有:背景,飞机,炮弹,和爆炸后的动作。
背景、飞机、炮弹,都需要的属性有:图像,绘图坐标X,Y。飞机和炮弹需要运动速度,炮弹是单独绘制,需要Height和Width。都需要用到的方法就是:绘图drawImage。
所以,可以新建一个公共的父类,把所有对象需要的属性、方法放进去,被其他类继承。属性用private修饰,留出接口。
GameObject.java 类:
package com.qin.game;
import java.awt.*;
public class GameObject {
private Image img;
private double x,y;
private int speed;
private int width, height;
//重载构造器
public GameObject() {
}
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;
}
public GameObject(Image img, double x, double y){
this.img = img;
this.x = x;
this.y = y;
}
//接口
public void setImg(Image img) {
this.img = img;
}
public Image getImg() {
return img;
}
public void setX(double x) {
this.x = x;
}
public double getX() {
return x;
}
public void setY(double y) {
this.y = y;
}
public double getY() {
return y;
}
public void setSpeed(int speed) {
this.speed = speed;
}
public int getSpeed() {
return speed;
}
public void setWidth(int width) {
this.width = width;
}
public int getWidth() {
return width;
}
public void setHeight(int height) {
this.height = height;
}
public int getHeight() {
return height;
}
// 绘制物体程序
public void drawImage(Graphics g){
g.drawImage(img,(int)x,(int)y,null);
}
//物体的矩形
public Rectangle getRect(){
return new Rectangle((int)x,(int)y,width,height);
}
}
在GameObject类中,drawImage方法需要用到img图像,所以我们还需要一个类可以读取图片以供drawImage使用。
GameUtil.java 类
package com.qin.game;
import java.awt.*;
import java.awt.image.BufferedImage;
impor