为了保持我的编程技能,最近我用Java和JavaFx 2.0构建了一个版本的这个游戏(Block blaster)。由于只是为了自己的利益,所以没有考虑软件模式或设计,因此所有的游戏逻辑都在GUI类中,随着功能的增加,GUI类变得越来越臃肿。最后,我决定重构代码库,将游戏逻辑和模型与表示(GUI)分离。
经过一些研究,我决定使用类似MVC或MVP的东西。在这样做时,我决定动画(块在发射时向上滑动,块在从游戏中移除时闪烁等)应该成为视图层的一部分。
这会导致的问题是,当用户启动一个块时,控制器告诉视图移动块,它会为动画创建JavaFx
在旧的(恶劣的)实现中,我使用
有没有一种等待JavaFx动画完成的方法(而不是使应用程序线程休眠),或者有没有不同的设计模式可以帮助避免这些问题? 来自控制器的代码
经过一些研究,我决定使用类似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)