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 篇原創文章 · 獲贊 59 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章