该代码很简单:通过查询GameGraphics.Count属性检测是否已经加载了游戏图形;如果尚未加载,那么从Ball.png资源中添加图形。
程序清单4-9展示了Reset函数。
程序清单4-9 Bounce 游戏的Reset 函数
/// <summary>
/// Reset the game
/// </summary>
public override void Reset()
{
CObjBall ball;
// Allow the base class to do its work
base.Reset();
// Clear any existing game objects.
GameObjects.Clear();
// Create a new ball. This will automatically generate a random position
// for itself.
ball = new CObjBall(this);
// Add the ball to the game engine
GameObjects.Add(ball);
}
这段代码首先调用GameObjects.Clear函数删除所有存在的游戏对象。然后创建本项目中CObjBall类(稍后将介绍该类)的一个实例,并将它添加到GameObjects集合中。
2. CobjBall类
CObjBall类从游戏引擎的CGameObjectGDIBase类继承,提供了使游戏中的小球能够移动及显示的功能。我们首先声明一些类变量,如程序清单4-10所示。
程序清单4-10 CObjBall中的类级别变量声明
// The velocity of the ball in the x and y axes
private float _xadd = 0;
private float _yadd = 0;
// Our reference to the game engine.
// Note that this is typed as CBounceGame, not as CGameEngineGDIBase
private CBounceGame _myGameEngine;
小球的类构造函数中包含了一个名为gameEngine的CBounceGame类型的参数,您也许会思考参数为什么不是CGameEngineGDIBase类?这是因为CBounceGame继承于引擎的基类,我们当然可以用它来调用基类,同时,用这种方式声明引擎的引用允许我们能够调用在继承类中创建的任何附加函数。
在_myGameEngine变量中设置一个对引擎对象的引用后,构造函数可以对小球进行初始化。包括设置其Width及Height(都从所加载的Bitmap对象中获取),然后再随机设置一个位置和速度。如程序清单4-11所示。
程序清单4-11 Ball对象的类构造函数
/// <summary>
/// Constructor. Require an instance of our own CBounceGame class as a
/// parameter.
/// </summary>
public CObjBall(CBounceGame gameEngine) : base(gameEngine)
{
// Store a reference to the game engine as its derived type
_myGameEngine = gameEngine;
// Set the width and height of the ball. Retrieve these from the loaded
//bitmap.
Width = _myGameEngine.GameGraphics["Ball"].Width;
Height = _myGameEngine.GameGraphics["Ball"].Height;
// Set a random position for the ball's starting location.
XPos = _myGameEngine.Random.Next(0, (int)(_myGameEngine.GameForm.Width - Width));
YPos = _myGameEngine.Random.Next(0, (int)(_myGameEngine.GameForm.Height / 2));
// Set a random x velocity. Keep looping until we get a non-zero value.
while (_xadd == 0)
{
_xadd = _myGameEngine.Random.Next(-4, 4);
}
// Set a random y velocity. Zero values don't matter here as this value
// will be affected by our simulation of gravity.
_yadd = (_myGameEngine.Random.Next(5, 15)) / 10;
}
注:以上内容图略,图片内容请参考原图书