上图
写在前面
技术源于分享,所以今天抽空把自己之前用java做过的小游戏整理贴出来给大家参考学习。java确实不适合写桌面应用,这里只是通过这个游戏让大家理解oop面向对象编程的过程,纯属娱乐。代码写的很简单,也很容易理解,并且注释写的很清楚了,还有问题,自己私下去补课学习。
完整代码
敌飞机
import java.util.Random;
敌飞机: 是飞行物,也是敌人
public class Airplane extends FlyingObject implements Enemy {
private int speed = 3; //移动步骤
/** 初始化数据 */
public Airplane(){
this.image = ShootGame.airplane;
width = image.getWidth();
height = image.getHeight();
y = -height;
Random rand = new Random();
x = rand.nextInt(ShootGame.WIDTH - width);
}
/** 获取分数 */
@Override
public int getScore() {
return 5;
}
/** //越界处理 */
@Override
public boolean outOfBounds() {
return y>ShootGame.HEIGHT;
}
/** 移动 */
@Override
public void step() {
y += speed;
}
}
分数奖励
/**
* 奖励
*/
public interface Award {
int DOUBLE_FIRE = 0; //双倍火力
int LIFE = 1; //1条命
/** 获得奖励类型(上面的0或1) */
int getType();
}
蜜蜂
import java.util.Random;
/** 蜜蜂 */
public class Bee extends FlyingObject implements Award{
private int xSpeed = 1; //x坐标移动速度
private int ySpeed = 2; //y坐标移动速度
private int awardType; //奖励类型
/** 初始化数据 */
public Bee(){
this.image = ShootGame.bee;
width = image.getWidth();
height = image.getHeight();
y = -height;
Random rand = new Random();
x = rand.nextInt(ShootGame.WIDTH - width);
awardType = rand.nextInt(2); //初始化时给奖励
}
/** 获得奖励类型 */
public int getType(){
return awardType;
}
/** 越界处理 */
@Override
public boolean outOfBounds() {
return y>ShootGame.HEIGHT;
}
/** 移动,可斜着飞 */
@Override
public void step() {
x += xSpeed;
y += ySpeed;
if(x > ShootGame.WIDTH-width){
xSpeed = -1;
}
if(x < 0){
xSpeed = 1;
}
}
}
子弹类:是飞行物体
/**
* 子弹类:是飞行物
*/
public class Bullet extends FlyingObject {
private int speed = 3; //移动的速度
/** 初始化数据 */
public Bullet(int x,int y){
this.x = x;
this.y = y;
this.image = ShootGame.bullet;
}
/** 移动 */
@Override
public void step(){
y-=speed;
}
/** 越界处理 */
@Override
public boolean outOfBounds() {
return y<-height;
}
}
敌人的分数
/**
* 敌人,可以有分数
*/
public interface Enemy {
/** 敌人的分数 */
int getScore();
}
飞行物(敌机,蜜蜂,子弹,英雄机)
import java.awt.image.BufferedImage;
/**
* 飞行物(敌机,蜜蜂,子弹,英雄机)
*/
public abstract class FlyingObject {
protected int x; //x坐标
protected int y; //y坐标
protected int width; //宽
protected int height; //高
protected BufferedImage image; //图片
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public BufferedImage getImage() {
return image;
}
public void setImage(BufferedImage image) {
this.image = image;
}
/**
* 检查是否出界
* @return true 出界与否
*/
public abstract boolean outOfBounds();
/**
* 飞行物移动一步
*/
public abstract void step();
/**
* 检查当前飞行物体是否被子弹(x,y)击(shoot)中
* @param Bullet 子弹对象
* @return true表示被击中了
*/
public boolean shootBy