1.8.2 游戏引擎
使用VB的事件驱动机制,可以考虑编写3个主要的事件来实现游戏开发方案中描述的行为:
(1) 当窗体加载时,可以创建第一个方块。
(2) 在窗体的KeyPress事件中,可以处理来自用户的键盘输入。
(3) 使用一个定时器控件可以实现“在每个时钟设置点调用Down方法”的功能,从而产生出预想的方块下落效果。正如后面将要介绍的内容所述,当创建高速运行的游戏时,我们并不推荐使用定时器控件。但是这里的情况有所不同。
编写伪代码非常有助于验证类图的正确性,可以查看程序是否使用了全部的方法和属性,并验证是否能够利用这些类成员获得游戏开发方案所声明的结果。本游戏程序的伪代码如以下代码段所示:
Form_Load
Creates an object (named currentBlock) of block class
因为要在其他所有的事件中使用currentBlock对象,所以该对象的使用范围必须与窗体的使用范围一致。
Form_KeyPress
If Left Arrow was pressed, call Left method of CurrentBlock
If Right Arrow was pressed, call Right method of CurrentBlock
If Up Arrow was pressed, call Rotate method of CurrentBlock
If Down Arrow was pressed, call Down method of CurrentBlock
在上面的伪代码中,使用键盘上的向上箭头键来旋转方块、使用向下箭头键来强制方块加速下落、使用向右箭头键和向左箭头键使方块在水平方向上移动。
游戏引擎的核心是定时器事件。回顾一下游戏开发方案,我们就可以确定此处必须执行的操作:使方块下落、根据游戏规则停止方块下落、查看是否存在完整的水平线、检查游戏是否结束。执行这些操作的参考伪代码如下所示:
If there is no block below CurrentBlock,
and the CurrentBlock didn't reach the bottom of the screen then
Call the Down method of CurrentBlock
Else
Stop the block
If it's at the top of the screen then
The game is over
If we filled any horizontal lines then
Increase the game score
Erase the line
Create a new block at the top of the screen
分析以上代码,可以发现有些特征是当前类图所没有考虑到的。例如,怎么查看当前方块下是否存在其他方块?如何删除游戏者努力形成的水平线?关于这些内容,我们将在接下来的章节讨论。






