Java打飞机游戏【1】基础工具类

这是飞机大战游戏的基础工具类代码及解释,其他的也在博客中

基础工具类包含三各类,统一放在com.airbattle.gameproperty包下

类名 用途
Image 存放游戏元素的图像、图像长宽
Position

位置类,包含x,y坐标

Rect

矩形类,游戏元素占用的矩形框的坐标,包含左上角的坐标(x1,y1),右下角的坐标(x2,y2)

代码较为简单,直接看代码

Image类

package com.airbattle.gameproperty;

import javax.swing.ImageIcon;

public class Image {
	public java.awt.Image img;    //Java提供的图像类,可以直接在窗口中绘制的图像
	public int width;    //图像的高和宽
	public int height;

    //构造函数,参数为:
    //filename:图像文件的路径,width,height为图像的宽和高
	public Image(String filename, int width, int height) {
		this.img = new ImageIcon(filename).getImage();
		this.height = height;
		this.width = width;
		//System.out.println("获取到图像文件名、长度、高度");
	}
}

因为每种游戏元素对应的图像是不变的,所以在其他类中,直接声明成静态常量,在程序启动时读取一次图像

Position类

package com.airbattle.gameproperty;

//存放游戏元素的x,y坐标
public class Position {
	public Position(int x, int y) {
		this.x = x;
		this.y = y;
		//System.out.println("创建了位置对象: ( "+ x + ", " + y + " )");
	}
	public int x;
	public int y;

}

Rect类

package com.airbattle.gameproperty;

public class Rect {
    //x1,y1是矩形左上角的坐标
    //x2,y2是矩形右上角的坐标
    //x1<x2,y1<y2永远成立
	public int x1;
	public int y1;
	public int x2;
	public int y2;
    //构造函数,传入矩形左上角坐标,矩形宽和高
	public Rect(int x, int y, int width, int height) {
		this.x1 = x;
		this.y1 = y;
		this.x2 = x + height;
		this.y2 = y + width;
	}
	

    //判断两个矩形是否相撞
    //判断的算法是:
    //取矩形1的四个角的顶点,判断顶点是否在矩形2中
    //如果有一个点在,则发生了相撞
	public boolean hit(Rect rect) {
		if (this.pointInRect(rect.x1, rect.y1) 
				|| this.pointInRect(rect.x1, rect.y2)
				|| this.pointInRect(rect.x2, rect.y1)
				|| this.pointInRect(rect.x2, rect.y2))
		return true;
		return false;
	}
	
    //判断一个点是否在矩形中
	public boolean pointInRect(int x, int y) {
		if (x>=this.x1 && x<=this.x2 && y>=this.y1 && y<=this.y2)
			return true;
		return false;
	}
}

这就是所有的工具类,这些类将服务于上层的类。

发布了86 篇原创文章 · 获赞 56 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/WilliamCode/article/details/103788020
今日推荐