Simple DirectMedia Layer: Gaming Platform for C++, Java, and More
Stop here and quickly look at Mix_PlayChannel(), which adds explosion noises at appropriate conditions. You're actually using three channels simultaneously in this game: one each for music, shots, and explosions respectively because at any given moment you may need to output up to all three at once. Otherwise, you would be continuously cutting away from one sound to play another sound and the soundtrack would be a choppy mess. By the way, you loaded the sounds earlier with a call such as:
127 sounds[MUSIC_WAV] = Mix_LoadWAV(DATAFILE("music.wav"));
Okay, back to the code:
474 // . . . 475 /* Draw the aliens, shots, player, and explosions */ 476 for ( i=0; i<MAX_ALIENS; ++i ) { 477 if ( aliens[i].alive ) { 478 DrawObject(&aliens[i]); 479 } 480 } 481 // . . . 494 UpdateScreen(); 495 496 /* Loop the music */ 498 if ( ! Mix_PlayingMusic() ) { 499 Mix_PlayMusic(music, 0); 500 } 506 507 /* Check for keyboard abort */ 508 if ( keys[SDLK_ESCAPE] == SDL_PRESSED ) { 509 player.alive = 0; 510 } 511 } 512 513 /* Wait for the player to finish exploding */ 514 while ( Mix_Playing(EXPLODE_WAV) ) { 515 WaitFrame(); 516 } 517 Mix_HaltChannel(-1); 518 return; 519 } 520
All right, I haven't been able to show every single thing, such as UpdateScreen(), which walks through a list of all the bitmaps you are going to display and blits them to the screen. You can follow this on your own copy of the source!
Conclusion
Even putting together a conventional 2D shooter game in 500-odd lines of code with music and realtime play is a pretty good feat in my imagination. And of course the same code can be compiled and linked to run on Windows and Linux platforms and a lot more. In some respects, you've barely scratched the surface and if you are encouraged to give SDL a try, then I think I've met my goal for this article!
About the Author
Victor Volkman has been writing for C/C++ Users Journal and other programming journals since the late 1980s. He is a graduate of Michigan Tech and a faculty advisor board member for the Washtenaw Community College CIS department. Volkman is the editor of numerous books, including C/C++ Treasure Chest and is the owner of Loving Healing Press. He can help you in your quest for open source tools and libraries; just drop send an email to sysop@HAL9K.com
Page 3 of 3
This article was originally published on April 3, 2008