Java.坦克大战小游戏【2.0】

任务

代码
增加 Wall 类,

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;

public class Wall {

    int x,y,w,h;
    TankClient tc = null;
    public Wall(int x, int y,int w,int h, TankClient tc) {
        super();
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
        this.tc = tc;
    }

    public void draw(Graphics g) {
        Color c = g.getColor();
        g.setColor(Color.GRAY);
        g.fillRect(x, y, w, h);
        g.setColor(c);
    }

    public Rectangle getRect() {
        return new Rectangle(x,y,w,h);
    }

}

在 Missile 类中判断子弹与墙是否相撞

//判断该子弹是否击中墙
    public boolean hitWall(Wall w) {
        if(this.live && this.getRect().intersects(w.getRect())) {
            this.live = false;
            return true;
        }
        return false;
    }

在 Tank 类中增加记录前一次坦克位置的 oldX 和 oldY,并判断坦克与墙是否相撞

//撞墙
    public boolean strikeWall(Wall w) {
        if(this.live && this.getRect().intersects(w.getRect())) {
            this.stay();
            return true;
        }
        return false;
    }
    public void stay() {
        this.x = oldX;
        this.y = oldY;
    }

最后在 TankClient 类中定义出 Wall 类的实例,画出墙

猜你喜欢

转载自blog.csdn.net/liyuanyue2017/article/details/80271181