Game Programming with the Simple DirectMedia Layer

Put the library behind Tux Racer and the Linux version of Civilization into your game.
Loading Resources

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.

The Main Loop

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.

______________________

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState