【发布时间】:2012-11-11 00:26:46
【问题描述】:
为了提高自己的编码技能,我最近使用 JavaFx 2.0 在 Java 中构建了 this game(Block blaster) 版本。因为这只是为了我的利益,没有真正考虑软件模式或设计,所以所有的游戏逻辑最终都在 GUI 类中,随着我添加功能,它变得越来越臃肿。我最终决定重构代码库,将游戏逻辑和模型与演示 (GUI) 分开。
经过一些研究,我决定使用 MVC 或 MVP 之类的东西。在这样做的过程中,我决定动画(方块在触发时向上滑动游戏网格,方块在从游戏中移除时闪烁等)将成为视图层的一部分。
这导致的问题是,当用户启动一个块并且控制器告诉视图移动该块时,它会为动画创建 JavaFx timeline 并调用 timeline.play()。这样做不会导致程序流在动画发生时在视图中暂停,因此视图方法返回只是刚刚开始动画,这意味着控制器然后继续检查该块是否已生成一组块如果是这样,在移动动画到达任何地方之前删除它们。
在旧的(讨厌的)实现中,我使用 timeline.onFinish 在动画完成后调用块组检查,但由于 timeline 现在在视图中,而控制器中的检查功能我不知道如何将其放入我的新设计中。
有没有办法等待 JavaFx 动画完成(不让应用程序线程休眠),或者我应该使用不同的设计模式来帮助避免这些问题?
来自控制器的代码
public void fire()
{
//Get the current column the launcher is in.
int x = launcher.getX(), startY = launcher.getY();
//Find the next available block in the column.
int endY;
for(endY = h; endY > 0 && blockMap[endY - 1][x] == null; endY--){}
//Create a new block of the same colour and location as that on the launcher.
addBlock(x, launcher.getY(), getCurrentColourAndRotate());
//Move the block in the GUI and model (this will trigger the animation in the GUI)
moveBlock(x, startY, x, endY);
//Remove any block groups that have been made.
checkBlock(blockMap[endY][x]);
//Remove any blocks now not connected to the top of the game grid
removeUnconnectedBlocks();
}
示例游戏截图
(来源:myhappygames.com)
【问题讨论】: