Java练手项目--小游戏:飞机大战

飞机大战

一周前开始学习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
  • 0
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值