上图
写在后面
技术源于分享,所以明天抽空把本人之前用 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(Bullet bullet){
int x = bullet.x; // 子弹横坐标
int y = bullet.y; // 子弹纵坐标
return this.x<x && x<this.x+width && this.y<y && y<this.y+height;
}
}
英雄机
import java.awt.image.BufferedImage;
/**
* 英雄机: 是飞行物
*/
public class Hero extends FlyingObject{private BufferedImage[] images = {}; // 英雄机图片
private int index = 0; // 英雄机图片切换索引
private int doubleFire; // 双倍火力
private int life; // 命
/** 初始化数据 */
public Hero(){
life = 3; // 初始 3 条命
doubleFire = 0; // 初始火力为 0
images = new BufferedImage[]{ShootGame.hero0, ShootGame.hero1}; // 英雄机图片数组
image = ShootGame.hero0; // 初始为 hero0 图片
width = image.getWidth();
height = image.getHeight();
x = 150;
y = 400;
}
/** 获取双倍火力 */
public int isDoubleFire() {return doubleFire;}
/** 设置双倍火力 */
public void setDoubleFire(int doubleFire) {this.doubleFire = doubleFire;}
/** 减少火力 */
public void addDoubleFire(){doubleFire = 40;}
/** 增命 */
public void addLife(){ // 增命
life++;
}
/** 减命 */
public void subtractLife(){ // 减命
life--;
}
/** 获取命 */
public int getLife(){return life;}
/** 以后物体挪动了一下,绝对间隔,x,y 鼠标地位 */
public void moveTo(int x,int y){
this.x = x - width/2;
this.y = y - height/2;
}
/** 越界解决 */
@Override
public boolean outOfBounds() {return false;}
/** 发射子弹 */
public Bullet[] shoot(){
int xStep = width/4; // 4 半
int yStep = 20; // 步
if(doubleFire>0){ // 双倍火力
Bullet[] bullets = new Bullet[2];
bullets[0] = new Bullet(x+xStep,y-yStep); //y-yStep(子弹距飞机的地位)
bullets[1] = new Bullet(x+3*xStep,y-yStep);
return bullets;
}else{ // 单倍火力
Bullet[] bullets = new Bullet[1];
bullets[0] = new Bullet(x+2*xStep,y-yStep);
return bullets;
}
}
/** 挪动 */
@Override
public void step() {if(images.length>0){image = images[index++/10%images.length]; // 切换图片 hero0,hero1
}
}
/** 碰撞算法 */
public boolean hit(FlyingObject other){
int x1 = other.x - this.width/2; // x 坐标最小间隔
int x2 = other.x + this.width/2 + other.width; // x 坐标最大间隔
int y1 = other.y - this.height/2; // y 坐标最小间隔
int y2 = other.y + this.height/2 + other.height; // y 坐标最大间隔
int herox = this.x + this.width/2; // 英雄机 x 坐标中心点间隔
int heroy = this.y + this.height/2; // 英雄机 y 坐标中心点间隔
return herox>x1 && herox<x2 && heroy>y1 && heroy<y2; // 区间范畴内为撞上了
}
}
游戏启动主类
import java.awt.Font;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
*/
public class ShootGame extends JPanel {
public static final int WIDTH = 400; // 面板宽
public static final int HEIGHT = 654; // 面板高
/** 游戏的以后状态: START RUNNING PAUSE GAME_OVER */
private int state;
private static final int START = 0;
private static final int RUNNING = 1;
private static final int PAUSE = 2;
private static final int GAME_OVER = 3;
private int score = 0; // 得分
private Timer timer; // 定时器
private int intervel = 1000 / 100; // 工夫距离(毫秒)
public static BufferedImage background;
public static BufferedImage start;
public static BufferedImage airplane;
public static BufferedImage bee;
public static BufferedImage bullet;
public static BufferedImage hero0;
public static BufferedImage hero1;
public static BufferedImage pause;
public static BufferedImage gameover;
private FlyingObject[] flyings = {}; // 敌机数组
private Bullet[] bullets = {}; // 子弹数组
private Hero hero = new Hero(); // 英雄机
static { // 动态代码块,初始化图片资源
try {
background = ImageIO.read(ShootGame.class
.getResource("background.png"));
start = ImageIO.read(ShootGame.class.getResource("start.png"));
airplane = ImageIO
.read(ShootGame.class.getResource("airplane.png"));
bee = ImageIO.read(ShootGame.class.getResource("bee.png"));
bullet = ImageIO.read(ShootGame.class.getResource("bullet.png"));
hero0 = ImageIO.read(ShootGame.class.getResource("hero0.png"));
hero1 = ImageIO.read(ShootGame.class.getResource("hero1.png"));
pause = ImageIO.read(ShootGame.class.getResource("pause.png"));
gameover = ImageIO
.read(ShootGame.class.getResource("gameover.png"));
} catch (Exception e) {e.printStackTrace();
}
}
/** 画 */
@Override
public void paint(Graphics g) {g.drawImage(background, 0, 0, null); // 画背景图
paintHero(g); // 画英雄机
paintBullets(g); // 画子弹
paintFlyingObjects(g); // 画飞行物
paintScore(g); // 画分数
paintState(g); // 画游戏状态
}
/** 画英雄机 */
public void paintHero(Graphics g) {g.drawImage(hero.getImage(), hero.getX(), hero.getY(), null);
}
/** 画子弹 */
public void paintBullets(Graphics g) {for (int i = 0; i < bullets.length; i++) {Bullet b = bullets[i];
g.drawImage(b.getImage(), b.getX() - b.getWidth() / 2, b.getY(),
null);
}
}
/** 画飞行物 */
public void paintFlyingObjects(Graphics g) {for (int i = 0; i < flyings.length; i++) {FlyingObject f = flyings[i];
g.drawImage(f.getImage(), f.getX(), f.getY(), null);
}
}
/** 画分数 */
public void paintScore(Graphics g) {
int x = 10; // x 坐标
int y = 25; // y 坐标
Font font = new Font(Font.SANS_SERIF, Font.BOLD, 22); // 字体
g.setColor(new Color(0xFF0000));
g.setFont(font); // 设置字体
g.drawString("SCORE:" + score, x, y); // 画分数
y=y+20; // y 坐标增 20
g.drawString("LIFE:" + hero.getLife(), x, y); // 画命
}
/** 画游戏状态 */
public void paintState(Graphics g) {switch (state) {
case START: // 启动状态
g.drawImage(start, 0, 0, null);
break;
case PAUSE: // 暂停状态
g.drawImage(pause, 0, 0, null);
break;
case GAME_OVER: // 游戏终止状态
g.drawImage(gameover, 0, 0, null);
break;
}
}
public static void main(String[] args) {JFrame frame = new JFrame("Fly");
ShootGame game = new ShootGame(); // 面板对象
frame.add(game); // 将面板增加到 JFrame 中
frame.setSize(WIDTH, HEIGHT); // 设置大小
frame.setAlwaysOnTop(true); // 设置其总在最上
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 默认敞开操作
frame.setIconImage(new ImageIcon("images/icon.jpg").getImage()); // 设置窗体的图标
frame.setLocationRelativeTo(null); // 设置窗体初始地位
frame.setVisible(true); // 尽快调用 paint
game.action(); // 启动执行}
/** 启动执行代码 */
public void action() {
// 鼠标监听事件
MouseAdapter l = new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) { // 鼠标挪动
if (state == RUNNING) { // 运行状态下挪动英雄机 -- 随鼠标地位
int x = e.getX();
int y = e.getY();
hero.moveTo(x, y);
}
}
@Override
public void mouseEntered(MouseEvent e) { // 鼠标进入
if (state == PAUSE) { // 暂停状态下运行
state = RUNNING;
}
}
@Override
public void mouseExited(MouseEvent e) { // 鼠标退出
if (state == RUNNING) { // 游戏未完结,则设置其为暂停
state = PAUSE;
}
}
@Override
public void mouseClicked(MouseEvent e) { // 鼠标点击
switch (state) {
case START:
state = RUNNING; // 启动状态下运行
break;
case GAME_OVER: // 游戏完结,清理现场
flyings = new FlyingObject[0]; // 清空飞行物
bullets = new Bullet[0]; // 清空子弹
hero = new Hero(); // 从新创立英雄机
score = 0; // 清空问题
state = START; // 状态设置为启动
break;
}
}
};
this.addMouseListener(l); // 解决鼠标点击操作
this.addMouseMotionListener(l); // 解决鼠标滑动操作
timer = new Timer(); // 主流程管制
timer.schedule(new TimerTask() {
@Override
public void run() {if (state == RUNNING) { // 运行状态
enterAction(); // 飞行物入场
stepAction(); // 走一步
shootAction(); // 英雄机射击
bangAction(); // 子弹打飞行物
outOfBoundsAction(); // 删除越界飞行物及子弹
checkGameOverAction(); // 查看游戏完结}
repaint(); // 重绘,调用 paint()办法
}
}, intervel, intervel);
}
int flyEnteredIndex = 0; // 飞行物入场计数
/** 飞行物入场 */
public void enterAction() {
flyEnteredIndex++;
if (flyEnteredIndex % 40 == 0) { // 400 毫秒生成一个飞行物 --10*40
FlyingObject obj = nextOne(); // 随机生成一个飞行物
flyings = Arrays.copyOf(flyings, flyings.length + 1);
flyings[flyings.length - 1] = obj;
}
}
/** 走一步 */
public void stepAction() {for (int i = 0; i < flyings.length; i++) { // 飞行物走一步
FlyingObject f = flyings[i];
f.step();}
for (int i = 0; i < bullets.length; i++) { // 子弹走一步
Bullet b = bullets[i];
b.step();}
hero.step(); // 英雄机走一步}
/** 飞行物走一步 */
public void flyingStepAction() {for (int i = 0; i < flyings.length; i++) {FlyingObject f = flyings[i];
f.step();}
}
int shootIndex = 0; // 射击计数
/** 射击 */
public void shootAction() {
shootIndex++;
if (shootIndex % 30 == 0) { // 300 毫秒发一颗
Bullet[] bs = hero.shoot(); // 英雄打出子弹
bullets = Arrays.copyOf(bullets, bullets.length + bs.length); // 扩容
System.arraycopy(bs, 0, bullets, bullets.length - bs.length,
bs.length); // 追加数组
}
}
/** 子弹与飞行物碰撞检测 */
public void bangAction() {for (int i = 0; i < bullets.length; i++) { // 遍历所有子弹
Bullet b = bullets[i];
bang(b); // 子弹和飞行物之间的碰撞查看
}
}
/** 删除越界飞行物及子弹 */
public void outOfBoundsAction() {
int index = 0; // 索引
FlyingObject[] flyingLives = new FlyingObject[flyings.length]; // 活着的飞行物
for (int i = 0; i < flyings.length; i++) {FlyingObject f = flyings[i];
if (!f.outOfBounds()) {flyingLives[index++] = f; // 不越界的留着
}
}
flyings = Arrays.copyOf(flyingLives, index); // 将不越界的飞行物都留着
index = 0; // 索引重置为 0
Bullet[] bulletLives = new Bullet[bullets.length];
for (int i = 0; i < bullets.length; i++) {Bullet b = bullets[i];
if (!b.outOfBounds()) {bulletLives[index++] = b;
}
}
bullets = Arrays.copyOf(bulletLives, index); // 将不越界的子弹留着
}
/** 查看游戏完结 */
public void checkGameOverAction() {if (isGameOver()==true) {state = GAME_OVER; // 扭转状态}
}
/** 查看游戏是否完结 */
public boolean isGameOver() {for (int i = 0; i < flyings.length; i++) {
int index = -1;
FlyingObject obj = flyings[i];
if (hero.hit(obj)) { // 查看英雄机与飞行物是否碰撞
hero.subtractLife(); // 减命
hero.setDoubleFire(0); // 双倍火力解除
index = i; // 记录碰上的飞行物索引
}
if (index != -1) {FlyingObject t = flyings[index];
flyings[index] = flyings[flyings.length - 1];
flyings[flyings.length - 1] = t; // 碰上的与最初一个飞行物替换
flyings = Arrays.copyOf(flyings, flyings.length - 1); // 删除碰上的飞行物
}
}
return hero.getLife() <= 0;}
/** 子弹和飞行物之间的碰撞查看 */
public void bang(Bullet bullet) {
int index = -1; // 击中的飞行物索引
for (int i = 0; i < flyings.length; i++) {FlyingObject obj = flyings[i];
if (obj.shootBy(bullet)) { // 判断是否击中
index = i; // 记录被击中的飞行物的索引
break;
}
}
if (index != -1) { // 有击中的飞行物
FlyingObject one = flyings[index]; // 记录被击中的飞行物
FlyingObject temp = flyings[index]; // 被击中的飞行物与最初一个飞行物替换
flyings[index] = flyings[flyings.length - 1];
flyings[flyings.length - 1] = temp;
flyings = Arrays.copyOf(flyings, flyings.length - 1); // 删除最初一个飞行物(即被击中的)
// 查看 one 的类型(敌人加分,处分获取)
if (one instanceof Enemy) { // 查看类型,是敌人,则加分
Enemy e = (Enemy) one; // 强制类型转换
score += e.getScore(); // 加分} else { // 若为处分,设置处分
Award a = (Award) one;
int type = a.getType(); // 获取处分类型
switch (type) {
case Award.DOUBLE_FIRE:
hero.addDoubleFire(); // 设置双倍火力
break;
case Award.LIFE:
hero.addLife(); // 设置加命
break;
}
}
}
}
/**
* 随机生成飞行物
*
* @return 飞行物对象
*/
public static FlyingObject nextOne() {Random random = new Random();
int type = random.nextInt(20); // [0,20)
if (type < 4) {return new Bee();
} else {return new Airplane();
}
}
}
原文链接:https://blog.csdn.net/wclxyn/…
版权申明:本文为 CSDN 博主「一只独孤的程序猿」的原创文章,遵循 CC 4.0 BY-SA 版权协定,转载请附上原文出处链接及本申明。
近期热文举荐:
1.1,000+ 道 Java 面试题及答案整顿(2021 最新版)
2. 别在再满屏的 if/ else 了,试试策略模式,真香!!
3. 卧槽!Java 中的 xx ≠ null 是什么新语法?
4.Spring Boot 2.5 重磅公布,光明模式太炸了!
5.《Java 开发手册(嵩山版)》最新公布,速速下载!
感觉不错,别忘了顺手点赞 + 转发哦!