Game Programming with the Simple DirectMedia Layer
Before Bounce can start up, it must load and initialize the resources it uses. Bounce has to initialize colors, load a few images and load the font it uses to draw text. Because the video mode was set using SDL_ANYFORMAT, all of these resources have to be converted to match an arbitrary display format. The following code creates a red pixel in the format we need:
SDL_PixelFormat *pf = screen->format; int red = SDL_MapRGB(pf, 0xff, 0x00, 0x00);
The SDL_PixelFormat structure is a description of the screen pixels, and SDL_MapRGB() converts a standard 24-bit RGB color representation into a pixel value that shows that color when drawn on that screen.
Loading images is slightly more complex:
SDL_Surface *s0, *s1;
s0 = SDL_LoadBMP(name);
s1 = SDL_DisplayFormat(s0);
SDL_SetColorKey(s1,
(SDL_SRCCOLORKEY |
SDL_RLEACCEL),
black);
SDL_FreeSurface(s0);
Core SDL includes SDL_LoadBMP(), which loads a .bmp format image as an SDL_Surface. SDL_image provides routines for loading many other image formats. The image is in the format in which it was created. We convert it to the display format using SDL_DisplayFormat(). SDL_SetColorKey() is used to tell SDL that when it copies (blits) this surface into another surface, it should ignore all the black pixels. I do this so that when I copy an image of the Earth onto the screen, none of the black background gets copied, and only the pixels inside the round shape of the Earth are touched. The SDL_RLEACCEL flag tells SDL to run length encode (RLE) the image. Using RLE-encoded images speeds up image copying.
Bounce uses one TrueType font but in three different sizes, two different colors and three different styles. Using the SDL_ttf library, I wrote a routine that loads a TrueType font, renders each of the ASCII characters in the range of 0-127 as an SDL_Surface, converts each character to match the screen and saves the height, width and advance of each letter so I can draw strings on the screen.
SDL provides an event-based input system, much like that used by X, Mac OS and Windows. When a key is pressed or the mouse is moved, an event is placed in a queue. The program can either wait for events using SDL_WaitEvent() or poll for events using SDL_PollEvent(). The main loop must process events, update the game state, draw the next frame and repeat until done.
The decision to wait or poll for events affects the overall structure of the game. I chose to wait for events and use a heartbeat timer to drive the action. I like this combination because it lets the program handle events whenever they occur while controlling CPU usage. Both of those qualities are important in networked games.
The timer is initialized using:
timer = SDL_AddTimer(10, timerCallback, NULL);
This tells SDL to call a routine named timerCallBack every ten milliseconds. My timer callback uses SDL_PushEvent() to send an event. Because timer callbacks run in a separate thread, they can send events even though the game is stopped, waiting for events. When it receives a timer event, Bounce checks to see if it is time to draw another frame. The timer makes sure the program doesn't try to draw more than 100 frames/second, while allowing the game to run at a slower rate if it must. On my machine, it runs at 85 frames/second, which matches the refresh rate of my monitor.
Bounce is organized into several different pages. The main loop handles events that are common among all the pages, such as quitting the program when you press Esc or pausing the game when you press F1. After the main loop has looked at an event, it passes the event to the current page. Each page is a function that takes an SDL_Event as its parameter. Each page has the responsibility to handle events, keep track of the time and draw the screen. Although this approach leads to some duplicate code, it gives the programmer greater flexibility, and it lends itself to an object-oriented design where each page is an instance of a page class. The following example shows parts of the main loop and illustrates how events are passed to the individual pages:
while ((!done) && SDL_WaitEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
done = true;
break;
case SDL_KEYDOWN:
switch(event.key.keysym.sym)
{
case SDLK_ESCAPE:
done = true;
break;
case SDLK_F1:
play = !play;
break;
}
break;
}
if (play &&
(!done) &&
(NULL != currentPage))
{
currentPage(&event);
}
}
The global variable currentPage points to the implementation of the current page. When one page wants to start another page, it initializes the new page and sets the pointer to that page. Bounce has three pages: the welcome page you see when the program starts, another page handles game play, and the “You Won/You Lost” message is the third page.
The event handler in the welcome page looks like:
switch (e->type)
{
case SDL_USEREVENT:
switch (e->user.code)
{
case MY_TIMEREVENT:
now = SDL_GetTicks();
dt = now - lastTime;
if (dt >= minFrameTime)
{
drawWelcome(dt);
lastTime = now;
}
break;
}
break;
case SDL_MOUSEBUTTONDOWN:
initBounce();
currentPage = bounce;
break;
}
When this code sees a timer event, it checks how long it has been since it last updated the screen and calls drawWelcome() to animate the screen. When it sees that a mouse button has been pressed, it switches to the game page by calling initBounce() to get it ready and then sets currentPage to point to the game page. The next time through, the main loop bounce() will be called.
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
| Dart: a New Web Programming Experience | May 07, 2013 |
- New Products
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- RSS Feeds
- New Products
- Trying to Tame the Tablet
- What's the tweeting protocol?
- Dart: a New Web Programming Experience
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.




3 hours 12 min ago
5 hours 35 min ago
22 hours 23 min ago
1 day 56 min ago
1 day 2 hours ago
1 day 2 hours ago
1 day 3 hours ago
1 day 7 hours ago
1 day 8 hours ago
1 day 10 hours ago