坦克大战图片版即在单机版的基础上将画出的坦克改成一张张的图片,提高界面的美观性。
其关键是把硬盘上的图片读到内存再画出来
private int step = 0;
/**
* 定义工具,不同操作系统的工具不同,其从硬盘读数据的方式可能不同
*/
private static Toolkit tk = Toolkit.getDefaultToolkit();
/**
* 定义为静态,即载入内存中只保留一份
*/
private static Image[] img = {
/**
* 使用工具类读取硬盘上的文件,类类型获取装载器获得资源的url(反射)
*/
tk.getImage(Explode.class.getClassLoader().getResource("images/0.gif")),
tk.getImage(Explode.class.getClassLoader().getResource("images/1.gif")),
tk.getImage(Explode.class.getClassLoader().getResource("images/2.gif")),
......
};
注意static的用法,另外static还有一种灵活的用法如:
static{
Image[] img = {
/**
* 使用工具类读取硬盘上的文件,类类型获取装载器获得资源的url(反射)
*/
tk.getImage(Tank.class.getClassLoader().getResource("images/tankL.gif")),
tk.getImage(Tank.class.getClassLoader().getResource("images/tankLU.gif")),
........
};
map.put(Direction.L, img[0]);
map.put(Direction.LU, img[1]);
........
}
这样可以在中间加入代码
本项目介绍了配置文件类Properties的使用:首先需要添加*.properties的文件,里面写入一些配置信息,如tankcount=10(中间不能有空格,之后也不需要分号),然后可以调用Properties类中的load方法,载入流文件,代码如下:
Properties prop = new Properties();
try {
prop.load(PropertyMgr.class
.getResourceAsStream("property/tank.properties"));
} catch (IOException e) {
e.printStackTrace();
}
int tankCount = Integer.parseInt(prop.getProperty("tankcount"));
本项目最后介绍了Singleton模式,即写一个配置的管理类,内存中只有一份对象实现对整个程序的配置管理,代码如下:
public class PropertyMgr {
static Properties prop = new Properties();
/**
* 写成静态内存中以有一份
*/
static {
try {
prop.load(PropertyMgr.class
.getResourceAsStream("property/tank.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 构造方法改成私有 使无法new新的PropertyMgr
*/
private PropertyMgr(){};
public static String getProperty(String key) {
return prop.getProperty(key);
}
}