Retro Gaming Hacks, Part 2: Add Paddles to Pong
Pages: 1, 2, 3, 4, 5, 6
Since we have moved the *screen pointer into the new GameData structure, change the variable declarations from the top of the main() function from:
SDL_Event event; // SDL events
SDL_Surface *screen; // main game window
to:
GameData game; // game data
SDL_Event event; // SDL events
And change the:
if ((screen =
SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 8, SDL_SWSURFACE ))
== NULL) {
to:
if ((game.screen =
SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, 8, SDL_SWSURFACE ))
== NULL) {'
(You just need to add a game. before the screen.) Now, right below the variable declarations, you need to initialize the GameData structure:
// Initialise game data
game.running = 1;
game.num_rects = 0;
The reason that you added the running variable to the GameData structure is so that you can check the game state from any subroutine that takes a pointer to the structure. With that in mind, let's change the handling of the SDL_QUIT event and the escape key ever so slightly, from:
if (event.type == SDL_QUIT ||
(event.type == SDL_KEYDOWN &&
event.key.keysym.sym == SDLK_ESCAPE))
return cleanUp( 0 );
to:
if (event.type == SDL_QUIT ||
(event.type == SDL_KEYDOWN &&
event.key.keysym.sym == SDLK_ESCAPE))
game.running = 0;
Change the entire last line, but nothing else, and add a new chunk of code right after the end of the event loop:
// If we have been told to exit, do so now
if (game.running == 0)
break;
This has the same effect as before, since breaking out of the main loop results in the program exiting through the use of the cleanUp() function, but keeping track of whether the game is running in the GameData structure allows you to modify it in function calls, which might prove useful later.
But the point of this section is supposed to be sprites, not the refactoring of the game's code to allow for extensibility! So let's return to sprites. Add the code shown in bold right after where you set the title bar's caption and hide the mouse cursor:
// Set window caption and turn off the mouse cursor
SDL_WM_SetCaption( "SDL Pong", "SDL Pong" );
SDL_ShowCursor( SDL_DISABLE );
// Get black and white colours
game.black = SDL_MapRGB( game.screen->format, 0x00, 0x00, 0x00 );
game.white = SDL_MapRGB( game.screen->format, 0xff, 0xff, 0xff );
// Initialise our sprite locations
resetSprites( &game, 0 );
We use SDL_MapRGB() (see sdldoc.csn.ul.ie/sdlmaprgb.php) to grab the color values of white and black (foreground and background), as dictated by the color map of the main window. Then call the resetSprites() function to draw the sprites.
And speaking of resetSprites(), you had better get around to writing it, or it won't be doing much good. Add its definition right below that of cleanUp():
// Function definitions
int cleanUp( int err );
void resetSprites( GameData *game, int erase );