项目地址:https://github.com/BeCuriousCat/Tetris
具体代码全在github上哈,下面只是部分代码。
我想系统的学习下编写一个完成游戏的过程,所以去看了小翼的俄罗斯方块的视频。
在看了一些(1-10)之后,记录一下,也做一下分享。
编程的人都知道使用魔数和硬编码是一个很不好的习惯,在视频中小翼教导了如何去使用一个XML文件作为一个配置文件,并且用反射生成实例。
大概是要完成这样的一个绘制游戏界面的功能,下面例子主要在JPanelGame中是实现。
如何调用配置表读取器
代码风格及习惯:要写成函数形式,一眼看明。
public GameConfig() throws DocumentException {
// 创建XML读取器
SAXReader reader = new SAXReader();
// 读取XML文件
Document doc = reader.read("config/cfg.xml");
// 获取XML文件的根节点
Element game = doc.getRootElement();
// 配置窗口参数
this.setUiConfig(game.element("frame"));
// 配置系统参数
this.setSystemConfig(game.element("system"));
// 配置数据访问参数
this.setDataConfig(game.element("frame"));
}
这是获取配置文件的一个函数,以下为例,使用从读取器中读到的数据构造一个Layer对象。
/**
* 配置窗口参数
*
* @param frame
* 配置文件窗口配置元素
* @return
*/
private void setUiConfig(Element frame) {
List<Element> layers = frame.elements("layer");
layersConfig = new ArrayList<LayerConfig>();
for (Element layer : layers) {
LayerConfig lc = new LayerConfig(layer.attributeValue("class"),
Integer.parseInt(layer.attributeValue("x")),
Integer.parseInt(layer.attributeValue("y")),
Integer.parseInt(layer.attributeValue("w")),
Integer.parseInt(layer.attributeValue("h")));
layersConfig.add(lc);
}
}
单例模式:在加载类的时候会执行static『』中的代码。实例化一个GameConfig实例,以后每次调用都是返回这个实例,就不重复的去读取配置文件,减少反应时间。
public class ConfigFactory {
private static GameConfig Game_CONFIG = null;
static{
try {
Game_CONFIG = new GameConfig();
} catch (Exception e) {
// TODO: handle exception
}
}
public static GameConfig getGamefig(){
return Game_CONFIG;
}
}
然后只要在cfg.xml中添加一条
<layer class="ui.LayerPoint" x="256" y="49" w="33" h="200"/>
<?xml version="1.0" encoding="UTF-8"?>
<game>
<frame width="1200" height="700" padding="16" windowSize="7">
<layer class="ui.LayerBackground" x="0" y="0" w="0" h="0"/>
<layer class="ui.LayerDataBase" x="40" y="32" w="334" h="279"/>
<layer class="ui.LayerDisk" x="40" y="343" w="334" h="279"/>
<layer class="ui.LayerGame" x="414" y="32" w="334" h="590"/>
<layer class="ui.LayerButton" x="788" y="32" w="334" h="124"/>
<layer class="ui.LayerNext" x="788" y="188" w="176" h="148"/>
<layer class="ui.LayerLevel" x="964" y="188" w="158" h="148"/>
<layer class="ui.LayerPoint" x="788" y="369" w="334" h="200"/>
</frame>
<system>
</system>
<data>
</data>
</game>
就会在界面中绘制一个新的矩形图层。这就是一个简单的图形框架了。
从XML->反射->图形绘制。只需要改变XMl配置,就可以动态的改变图形绘制。