【发布时间】:2009-10-13 16:15:35
【问题描述】:
我目前正在用 Java 开发一个小平台,并为它编写了自己的游戏引擎,名为Bonsai。现在我在问自己“我是否过度使用静力学?”。
一方面,它非常方便,因为我不必在每个类(如地图或玩家)中保留对游戏实例的引用。另一方面......我已经不得不去掉小程序支持,因为那里有很多静态的东西。
所以我的问题是,既然您可能比我更有经验的 Java 程序员,我应该摆脱所有的静态吗?如果是的话,什么是实现这样的有效方法:
public void draw(Graphics2D) {
if (this.game.time() > this.timer) {
this.game.image.draw(this.tiles[this.game.animation.get("tileAnim")], x, y, null)
}
}
代替:
public void draw(Graphics2D) {
if (Game.time() > this.timer) {
Image.draw(this.tiles[Animation.get("tileAnim")], x, y, null)
}
}
在地图编辑器中甚至更糟:
public void control() {
if(this.map.game.input.keyPressed(...)) {
this.map.game.sound.play(...);
}
}
编辑
根据答案,我决定有一个 GameObject 类,它为每个组件提供包装方法。地图、播放器等然后从它子类化,这样我所有的 this.game 调用都隐藏在幕后,它在前端看起来仍然不错:
public class GameObject {
private Game game;
public GameObject(Game g) {
game = g;
}
public Game Game() {
return game;
}
public GameAnimation Animation() {
return game.animation;
}
public GameInput Font() {
return game.input;
}
// ...
public long Time() {
return game.time();
}
}
现在代码如下所示:
public class Player() {
public Player(Game g, int xpos, int ypos) {
super(g);
// do other stuff
}
public void jump() {
// jump code
Sound().play("jump");
}
}
或者这是否是更糟糕的 Java?
EDIT2
好的,我已经在使用方法调用时遇到了问题,编译器给了我错误,因为它在原始版本中找不到我的子类 Game 的方法,我想我将在这里使用普通字段。
EDIT3
好的,我的 GameObject 类现在看起来像这样,一切正常,我可以重新实现小程序支持 :)
public class GameObject {
protected Game game;
protected GameAnimation animation;
protected GameFont font;
protected GameInput input;
protected GameImage image;
protected GameSound sound;
public GameObject(Game g) {
game = g;
animation = game.animation;
font = game.font;
input = game.input;
image = game.image;
sound = game.sound;
}
}
【问题讨论】:
-
在 Java 中最好有:
public Game getGame()或public Game game()