Building the Game
You can breathe a sigh of relief because you're finished making changes to the game engine for a little while. However, the real challenge of putting together the Meteor Defense game now awaits you. Fortunately, the game isn't too difficult to understand because you've already worked through a reasonably detailed game design. The next few sections guide you through the development of the game's code and resources.
Writing the Game Code
The code for the Meteor Defense game begins in the MeteorDefense.h header file, which is responsible for declaring the global variables used throughout the game, as well as a couple of useful functions. Listing 19.2 contains the code for this file.
Listing 19.2 The MeteorDefense.h Header File Declares Global Variables and Game-Specific Functions for the Meteor Defense Game
1: #pragma once 2: 3: //----------------------------------------------------------------- 4: // Include Files 5: //----------------------------------------------------------------- 6: #include <windows.h> 7: #include "Resource.h" 8: #include "GameEngine.h" 9: #include "Bitmap.h" 10: #include "Sprite.h" 11: #include "Background.h" 12: 13: //----------------------------------------------------------------- 14: // Global Variables 15: //----------------------------------------------------------------- 16: HINSTANCE _hInstance; 17: GameEngine* _pGame; 18: HDC _hOffscreenDC; 19: HBITMAP _hOffscreenBitmap; 20: Bitmap* _pGroundBitmap; 21: Bitmap* _pTargetBitmap; 22: Bitmap* _pCityBitmap; 23: Bitmap* _pMeteorBitmap; 24: Bitmap* _pMissileBitmap; 25: Bitmap* _pExplosionBitmap; 26: Bitmap* _pGameOverBitmap; 27: StarryBackground* _pBackground; 28: Sprite* _pTargetSprite; 29: int _iNumCities, _iScore, _iDifficulty; 30: BOOL _bGameOver; 31: 32: //----------------------------------------------------------------- 33: // Function Declarations 34: //----------------------------------------------------------------- 35: void NewGame(); 36: void AddMeteor();
As the listing reveals, the global variables for the Meteor Defense game largely consist of the different bitmaps that are used throughout the game. The starry background for the game is declared after the bitmaps (line 27), followed by the crosshair target sprite (line 28). Member variables storing the number of remaining cities, the score, and the difficulty level are then declared (line 29), along with the familiar game over Boolean variable (line 30).
The NewGame() function declared in the MeteorDefense.h file is important because it is used to set up and start a new game (line 35). Unlike the GameStart() function, which performs critical initialization tasks such as loading bitmaps, the NewGame() function deals with actually starting a new game once everything else is in place. The AddMeteor() function is a support function used to simplify the task of adding meteor sprites to the game (line 36). You find out more about how these functions work later in the hour.
The initialization of the game variables primarily takes place in the GameStart() function, which is shown in Listing 19.3.
Listing 19.3 The GameStart() Function Initializes the Bitmaps and Background for the Game, and Calls the NewGame() Function
1: void GameStart(HWND hWindow) 2: { 3: // Seed the random number generator 4: srand(GetTickCount()); 5: 6: // Create the offscreen device context and bitmap 7: _hOffscreenDC = CreateCompatibleDC(GetDC(hWindow)); 8: _hOffscreenBitmap = CreateCompatibleBitmap(GetDC(hWindow), 9: _pGame->GetWidth(), _pGame->GetHeight()); 10: SelectObject(_hOffscreenDC, _hOffscreenBitmap); 11: 12: // Create and load the bitmaps 13: HDC hDC = GetDC(hWindow); 14: _pGroundBitmap = new Bitmap(hDC, IDB_GROUND, _hInstance); 15: _pTargetBitmap = new Bitmap(hDC, IDB_TARGET, _hInstance); 16: _pCityBitmap = new Bitmap(hDC, IDB_CITY, _hInstance); 17: _pMeteorBitmap = new Bitmap(hDC, IDB_METEOR, _hInstance); 18: _pMissileBitmap = new Bitmap(hDC, IDB_MISSILE, _hInstance); 19: _pExplosionBitmap = new Bitmap(hDC, IDB_EXPLOSION, _hInstance); 20: _pGameOverBitmap = new Bitmap(hDC, IDB_GAMEOVER, _hInstance); 21: 22: // Create the starry background 23: _pBackground = new StarryBackground(600, 450); 24: 25: // Play the background music 26: _pGame->PlayMIDISong(TEXT("Music.mid")); 27: 28: // Start the game 29: NewGame(); 30: }
After loading the bitmaps for the game (lines 1420) and creating the starry background (line 23), the GameStart() function starts playing the background music (line 26). The function then finishes by calling the NewGame() function to start a new game (line 29).
The GameEnd() function plays a complementary role to the GameStart() function and cleans up after the game. Listing 19.4 contains the code for the GameEnd() function.
Listing 19.4 The GameEnd() Function Cleans Up After the Game
1: void GameEnd() 2: { 3: // Close the MIDI player for the background music 4: _pGame->CloseMIDIPlayer(); 5: 6: // Cleanup the offscreen device context and bitmap 7: DeleteObject(_hOffscreenBitmap); 8: DeleteDC(_hOffscreenDC); 9: 10: // Cleanup the bitmaps 11: delete _pGroundBitmap; 12: delete _pTargetBitmap; 13: delete _pCityBitmap; 14: delete _pMeteorBitmap; 15: delete _pMissileBitmap; 16: delete _pExplosionBitmap; 17: delete _pGameOverBitmap; 18: 19: // Cleanup the background 20: delete _pBackground; 21: 22: // Cleanup the sprites 23: _pGame->CleanupSprites(); 24: 25: // Cleanup the game engine 26: delete _pGame; 27: }
The first step in the GameEnd() function is to close the MIDI player (line 4). The bitmaps and sprites are then wiped away (lines 720), as well as the background (line 20). Finally, the sprites are cleaned up (line 23) and the game engine is destroyed (line 26).
The game screen in the Meteor Defense game is painted by the GamePaint() function, which is shown in Listing 19.5.
Listing 19.5 The GamePaint() Function Draws the Background, the Ground Bitmap, the Sprites, the Score, and the Game Over Message
1: void GamePaint(HDC hDC) 2: { 3: // Draw the background 4: _pBackground->Draw(hDC); 5: 6: // Draw the ground bitmap 7: _pGroundBitmap->Draw(hDC, 0, 398, TRUE); 8: 9: // Draw the sprites 10: _pGame->DrawSprites(hDC); 11: 12: // Draw the score 13: TCHAR szText[64]; 14: RECT rect = { 275, 0, 325, 50 }; 15: wsprintf(szText, "%d", _iScore); 16: SetBkMode(hDC, TRANSPARENT); 17: SetTextColor(hDC, RGB(255, 255, 255)); 18: DrawText(hDC, szText, -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER); 19: 20: // Draw the game over message, if necessary 21: if (_bGameOver) 22: _pGameOverBitmap->Draw(hDC, 170, 150, TRUE); 23: }
This GamePaint() function is responsible for drawing all the graphics for the game. The function begins by drawing the starry background (line 4), followed by the ground image (line 7). The sprites are drawn next (line 10), followed by the score (lines 1318). Notice that the score text is set to white (line 17), whereas the background is set to transparent for drawing the score so that the starry sky shows through the numbers in the score (line 16). The GamePaint() function finishes up by drawing the game over image, if necessary (lines 2122).
The GameCycle() function works closely with GamePaint() to update the game's sprites and reflect the changes onscreen. Listing 19.6 shows the code for the GameCycle()function.
Listing 19.6 The GameCycle() Function Randomly Adds Meteors to the Game Based on the Difficulty Level
1: void GameCycle() 2: { 3: if (!_bGameOver) 4: { 5: // Randomly add meteors 6: if ((rand() % _iDifficulty) == 0) 7: AddMeteor(); 8: 9: // Update the background 10: _pBackground->Update(); 11: 12: // Update the sprites 13: _pGame->UpdateSprites(); 14: 15: // Obtain a device context for repainting the game 16: HWND hWindow = _pGame->GetWindow(); 17: HDC hDC = GetDC(hWindow); 18: 19: // Paint the game to the offscreen device context 20: GamePaint(_hOffscreenDC); 21: 22: // Blit the offscreen bitmap to the game screen 23: BitBlt(hDC, 0, 0, _pGame->GetWidth(), _pGame->GetHeight(), 24: _hOffscreenDC, 0, 0, SRCCOPY); 25: 26: // Cleanup 27: ReleaseDC(hWindow, hDC); 28: } 29: }
Aside from the standard GameCycle() code that you've grown accustomed to seeing, this function doesn't contain a whole lot of additional code. The new code involves randomly adding new meteors, which is accomplished by calling the AddMeteor() function after using the difficulty level to randomly determine if a meteor should be added (lines 67).
The MouseButtonDown()function is where most of the game logic for the Meteor Defense game is located, as shown in Listing 19.7.
Listing 19.7 The MouseButtonDown() Function Launches a Missile Sprite Toward the Location of the Mouse Pointer
1: void MouseButtonDown(int x, int y, BOOL bLeft) 2: { 3: if (!_bGameOver && bLeft) 4: { 5: // Create a new missile sprite and set its position 6: RECT rcBounds = { 0, 0, 600, 450 }; 7: int iXPos = (x < 300) ? 144 : 449; 8: Sprite* pSprite = new Sprite(_pMissileBitmap, rcBounds, BA_DIE); 9: pSprite->SetPosition(iXPos, 365); 10: 11: // Calculate the velocity so that it is aimed at the target 12: int iXVel, iYVel = -6; 13: y = min(y, 300); 14: iXVel = (iYVel * ((iXPos + 8) - x)) / (365 - y); 15: pSprite->SetVelocity(iXVel, iYVel); 16: 17: // Add the missile sprite 18: _pGame->AddSprite(pSprite); 19: 20: // Play the fire sound 21: PlaySound((LPCSTR)IDW_FIRE, _hInstance, SND_ASYNC | 22: SND_RESOURCE | SND_NOSTOP); 23: 24: // Update the score 25: _iScore = max(--_iScore, 0); 26: } 27: else if (_bGameOver && !bLeft) 28: // Start a new game 29: NewGame(); 30: }
The MouseButtonDown() function handles firing a missile toward the target. The function first checks to make sure that the game isn't over and that the player clicked the left mouse button (line 3). If so, a missile sprite is created based on the position of the mouse (lines 69). The position is important first because it determines which gun is used to fire the missilethe left gun fires missiles toward targets on the left side of the game screen, whereas the right gun takes care of the right side of the screen. The target position is also important because it determines the trajectory and therefore the velocity of the missile (lines 1215).
After the missile sprite is created, the MouseButtonDown() function adds it to the game engine (line 18). A sound effect is then played to indicate that the missile has been fired (lines 21 and 22). Earlier in the hour during the design of the game, I mentioned how the score would be decreased slightly with each missile firing, which discourages inaccuracy in firing missiles because you can only build up your score by destroying meteors with the missiles. The score is decreased upon firing a missile, as shown in line 25. The last code in the MouseButtonDown() function takes care of starting a new game via the right mouse button if the game is over (lines 2729).
Another mouse-related function used in the Meteor Defense game is MouseMove(), which is used to move the crosshair target sprite so that it tracks the mouse pointer. This is necessary so that you are always in control of the target sprite with the mouse. Listing 19.8 shows the code for the MouseMove() function.
Listing 19.8 The MouseMove() Function Tracks the Mouse Cursor with the Target Sprite
1: void MouseMove(int x, int y) 2: { 3: // Track the mouse with the target sprite 4: _pTargetSprite->SetPosition(x - (_pTargetSprite->GetWidth() / 2), 5: y - (_pTargetSprite->GetHeight() / 2)); 6: }
The target sprite is made to follow the mouse pointer by simply calling the SetPosition() method on the sprite and passing in the mouse coordinates (lines 4 and 5). The position of the target sprite is calculated so that the target sprite always appears centered on the mouse pointer.
The SpriteCollision() function is called in response to sprites colliding, and is extremely important in the Meteor Defense game, as shown in Listing 19.9.
Listing 19.9 The SpriteCollision() Function Detects and Responds to Collisions Between Missiles, Meteors, and Cities
1: BOOL SpriteCollision(Sprite* pSpriteHitter, Sprite* pSpriteHittee) 2: { 3: // See if a missile and a meteor have collided 4: if ((pSpriteHitter->GetBitmap() == _pMissileBitmap && 5: pSpriteHittee->GetBitmap() == _pMeteorBitmap) || 6: (pSpriteHitter->GetBitmap() == _pMeteorBitmap && 7: pSpriteHittee->GetBitmap() == _pMissileBitmap)) 8: { 9: // Kill both sprites 10: pSpriteHitter->Kill(); 11: pSpriteHittee->Kill(); 12: 13: // Update the score 14: _iScore += 6; 15: _iDifficulty = max(50 - (_iScore / 10), 5); 16: } 17: 18: // See if a meteor has collided with a city 19: if (pSpriteHitter->GetBitmap() == _pMeteorBitmap && 20: pSpriteHittee->GetBitmap() == _pCityBitmap) 21: { 22: // Play the big explosion sound 23: PlaySound((LPCSTR)IDW_BIGEXPLODE, _hInstance, SND_ASYNC | 24: SND_RESOURCE); 25: 26: // Kill both sprites 27: pSpriteHitter->Kill(); 28: pSpriteHittee->Kill(); 29: 30: // See if the game is over 31: if (--_iNumCities == 0) 32: _bGameOver = TRUE; 33: } 34: 35: return FALSE; 36: }
The first collision detected in the SpriteCollision() function is the collision between a missile and a meteor (lines 47). You might be a little surprised by how the code is determining what kinds of sprites are colliding. In order to distinguish between sprites, you need a piece of information that uniquely identifies each type of sprite in the game. The bitmap pointer turns out being a handy and efficient way to identify and distinguish between sprites. Getting back to the collision between a missile and a meteor, the SpriteCollision() function kills both sprites (lines 10 and 11) and increases the score because a meteor has been successfully hit with a missile (line 14).
The difficulty level is also modified so that it gradually increases along with the score (line 15). It's worth pointing out that the game gets harder as the difficulty level decreases, with the maximum difficulty being reached at a value of 5 for the _iDifficulty global variable; the game is pretty much raining meteors at this level, which corresponds to reaching a score of 450. You can obviously tweak these values to suit your own tastes if you decide that the game gets difficult too fast or if you want to stretch out the time it takes for the difficulty level to increase.
The second collision detected in the SpriteCollision() function is between a meteor and a city (lines 19 and 20). If this collision takes place, a big explosion sound is played (lines 23 and 24), and both sprites are killed (lines 27 and 28). The number of cities is then checked to see if the game is over (lines 31 and 32) .
Earlier in the hour, you added a new SpriteDying()function to the game engine that allows you to respond to a sprite being destroyed. This function comes in quite handy in the Meteor Defense game because it allows you to conveniently create an explosion sprite any time a meteor sprite is destroyed. Listing 19.10 shows how this is made possible by the SpriteDying() function.
Listing 19.10 The SpriteDying() Function Creates an Explosion Whenever a Meteor Sprite Is Destroyed
1: void SpriteDying(Sprite* pSprite) 2: { 3: // See if a meteor sprite is dying 4: if (pSprite->GetBitmap() == _pMeteorBitmap) 5: { 6: // Play the explosion sound 7: PlaySound((LPCSTR)IDW_EXPLODE, _hInstance, SND_ASYNC | 8: SND_RESOURCE | SND_NOSTOP); 9: 10: // Create an explosion sprite at the meteor's position 11: RECT rcBounds = { 0, 0, 600, 450 }; 12: RECT rcPos = pSprite->GetPosition(); 13: Sprite* pSprite = new Sprite(_pExplosionBitmap, rcBounds); 14: pSprite->SetNumFrames(12, TRUE); 15: pSprite->SetPosition(rcPos.left, rcPos.top); 16: _pGame->AddSprite(pSprite); 17: } 18: }
The bitmap pointer of the sprite is used again to determine if the dying sprite is indeed a meteor sprite (line 4). If so, an explosion sound effect is played (lines 7 and 8), and an explosion sprite is created (lines 1116). Notice that the SetNumFrames() method is called to set the number of animation frames for the explosion sprite, as well as to indicate that the sprite should be destroyed after finishing its animation cycle (line 14). If you recall, this is one of the other important sprite-related features you added to the game engine earlier in the hour.
The remaining two functions in the Meteor Defense game are support functions that are completely unique to the game. The first one is NewGame(), which performs the steps necessary to start a new game (Listing 19.11).
Listing 19.11 The NewGame() Function Gets Everything Ready for a New Game
1: void NewGame() 2: { 3: // Clear the sprites 4: _pGame->CleanupSprites(); 5: 6: // Create the target sprite 7: RECT rcBounds = { 0, 0, 600, 450 }; 8: _pTargetSprite = new Sprite(_pTargetBitmap, rcBounds, BA_STOP); 9: _pTargetSprite->SetZOrder(10); 10: _pGame->AddSprite(_pTargetSprite); 11: 12: // Create the city sprites 13: Sprite* pSprite = new Sprite(_pCityBitmap, rcBounds); 14: pSprite->SetPosition(2, 370); 15: _pGame->AddSprite(pSprite); 16: pSprite = new Sprite(_pCityBitmap, rcBounds); 17: pSprite->SetPosition(186, 370); 18: _pGame->AddSprite(pSprite); 19: pSprite = new Sprite(_pCityBitmap, rcBounds); 20: pSprite->SetPosition(302, 370); 21: _pGame->AddSprite(pSprite); 22: pSprite = new Sprite(_pCityBitmap, rcBounds); 23: pSprite->SetPosition(490, 370); 24: _pGame->AddSprite(pSprite); 25: 26: // Initialize the game variables 27: _iScore = 0; 28: _iNumCities = 4; 29: _iDifficulty = 50; 30: _bGameOver = FALSE; 31: 32: // Play the background music 33: _pGame->PlayMIDISong(); 34: }
The NewGame() function starts off by clearing the sprite list (line 4), which is important because you don't really know what might have been left over from the previous game. The crosshair target sprite is then created (lines 710), as well as the city sprites (lines 1324). The global game variables are then set (lines 2730), and the background music is started up (line 33).
The AddMeteor() function is shown in Listing 19.12, and its job is to add a new meteor to the game at a random position and aimed at a random city.
Listing 19.12 The AddMeteor() Function Adds a New Meteor at a Random Position and Aimed at a Random City
1: void AddMeteor() 2: { 3: // Create a new meteor sprite and set its position 4: RECT rcBounds = { 0, 0, 600, 390 }; 5: int iXPos = rand() % 600; 6: Sprite* pSprite = new Sprite(_pMeteorBitmap, rcBounds, BA_DIE); 7: pSprite->SetNumFrames(14); 8: pSprite->SetPosition(iXPos, 0); 9: 10: // Calculate the velocity so that it is aimed at one of the cities 11: int iXVel, iYVel = (rand() % 4) + 3; 12: switch(rand() % 4) 13: { 14: case 0: 15: iXVel = (iYVel * (56 - (iXPos + 50))) / 400; 16: break; 17: case 1: 18: iXVel = (iYVel * (240 - (iXPos + 50))) / 400; 19: break; 20: case 2: 21: iXVel = (iYVel * (360 - (iXPos + 50))) / 400; 22: break; 23: case 3: 24: iXVel = (iYVel * (546 - (iXPos + 50))) / 400; 25: break; 26: } 27: pSprite->SetVelocity(iXVel, iYVel); 28: 29: // Add the meteor sprite 30: _pGame->AddSprite(pSprite); 31: }
The AddMeteor() function adds a new meteor to the game, and its code is probably a little longer than you expected simply because it tries to add meteors so that they are aimed at cities, as opposed to just zinging around the game screen aimlessly. Granted, a real meteor wouldn't target a city; but this is a game, and the idea is to challenge the player by forcing them to save cities from incoming meteors. So, in the world of Meteor Defense, the meteors act more like incoming nuclear warheads in that they tend to target cities.
The function begins by creating a meteor sprite and setting it to a random position along the top edge of the game screen (lines 48). The big section of code in the middle of the function takes care of setting the meteor's velocity so that it targets one of the four cities positioned along the bottom of the screen (lines 1127). I realize that this code looks a little tricky, but all that's going on is some basic trigonometry to figure out what velocity is required to get the meteor from point A to point B, where point A is the meteor's random position and point B is the position of the city. The AddMeteor() function ends by adding the new meteor sprite to the game engine (line 30).
That wraps up the code for the Meteor Defense game, which hopefully doesn't have your head spinning too much. Now you just need to put the resources together and you can start playing.