該代碼很簡(jiǎn)單:通過查詢GameGraphics.Count屬性檢測(cè)是否已經(jīng)加載了游戲圖形;如果尚未加載,那么從Ball.png資源中添加圖形。
程序清單4-9展示了Reset函數(shù)。
程序清單4-9 Bounce 游戲的Reset 函數(shù)
/// <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);
}
這段代碼首先調(diào)用GameObjects.Clear函數(shù)刪除所有存在的游戲?qū)ο?。然后?chuàng)建本項(xiàng)目中CObjBall類(稍后將介紹該類)的一個(gè)實(shí)例,并將它添加到GameObjects集合中。
2. CobjBall類
CObjBall類從游戲引擎的CGameObjectGDIBase類繼承,提供了使游戲中的小球能夠移動(dòng)及顯示的功能。我們首先聲明一些類變量,如程序清單4-10所示。
程序清單4-10 CObjBall中的類級(jí)別變量聲明
// 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;
小球的類構(gòu)造函數(shù)中包含了一個(gè)名為gameEngine的CBounceGame類型的參數(shù),您也許會(huì)思考參數(shù)為什么不是CGameEngineGDIBase類?這是因?yàn)镃BounceGame繼承于引擎的基類,我們當(dāng)然可以用它來調(diào)用基類,同時(shí),用這種方式聲明引擎的引用允許我們能夠調(diào)用在繼承類中創(chuàng)建的任何附加函數(shù)。
在_myGameEngine變量中設(shè)置一個(gè)對(duì)引擎對(duì)象的引用后,構(gòu)造函數(shù)可以對(duì)小球進(jìn)行初始化。包括設(shè)置其Width及Height(都從所加載的Bitmap對(duì)象中獲取),然后再隨機(jī)設(shè)置一個(gè)位置和速度。如程序清單4-11所示。
程序清單4-11 Ball對(duì)象的類構(gòu)造函數(shù)
/// <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;
}
注:以上內(nèi)容圖略,圖片內(nèi)容請(qǐng)參考原圖書