紧跟上篇博客
链接:JAVA实现飞机大战01
3. 加载图片的类,因为我们要加载很多图片,如果每加载一个写一个类,着实会增加代码的冗余,所以写一个图片的加载类
import java.awt.Image;
public class GameUtil{
private GameUtil(){ //私有说明紧随类,用类名调用
//工具类最好将构造器私有化
}
/*返回指定路径文件的图片对象
*/
public static Image getImage(String path){ //static方法存放在方法区中
BufferedImage bi =null;
try{
URL u=GameUtil.getClassLoadedr().getResource(path);//path就是要加载的图片的绝对路径
bi=ImageIO.read(u);//读取图片
}catch(IOException e){
e.printStackTrace();
}
return bi;//返回图片
}
}
- 加载背景和图片到桌面,代码加到lMyGameFrame框架的开头位置,
Image planeImage=GameUtil.getImage("images/plane.png");
Image bg =GameUtil.getImage("images/bg.png"); //在该工程下创建与`src`同级的包`images`
//paint方法自动被调用 g相当于画笔
public void paint(Graphics g) {//画图函数被封装起来,因为每个游戏的物体都要画图(方法),起始位置(常量),速度(常量)等属性所以讲游戏物体包装成GameObject类
g.drawImage(bg, 0, 0, null);
g.drawImage(planeImage,Constant.PLANE_BEGIN_LOCATIONX,Constant.PLANE_BEGIN_LOCATIONY,null);
}
GameObject类的代码
import java.awt.Graphics;
import java.awt.Image;
/*
* @游戏物体的父类
*
*/
public class GameObject {
Image img;
double x,y;
int speed;
int width,height;
public void drawSelf(Graphics g) {//画图片
g.drawImage(img, (int)x,(int)y,null);//img表示
}
public GameObject(Image img, double x, double y, int speed, int width, int height) {
super();
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) {
super();
this.img = img;
this.x = x;
this.y = y;
}
public GameObject() {//无参构造
}
}