HomeMultimedia Page 3 - Game Programming using SDL: Raw Graphics and Event Handling
Putting the Functions to Use - Multimedia
If you have found yourself struggling with pixel-level graphics and/or user input for your games, this is the article for you. You will learn how to handle these tasks using SDL. This is the second part of a series on game programming with SDL.
Now that both functions have been explained, let's see how to put one of them to use, i.e. putpixel(). For this I am defining a method called putyellowpixel() that places a yellow pixel at the center of the screen. It doesn't accept any parameter nor does it return any value.
void putyellowpixel() { int x, y; Uint32 yellow;
/* Map the color yellow to this display (R=0xff, G=0xFF, B=0x00) Note: If the display is palettized, you must set the palette first. */ yellow = SDL_MapRGB(screen->format, 0xff, 0xff, 0x00);
x = screen->w / 2; y = screen->h / 2;
/* Lock the screen for direct access to the pixels */ if ( SDL_MUSTLOCK(screen) ) { if ( SDL_LockSurface(screen) < 0 ) { fprintf(stderr, "Can't lock screen: %sn", SDL_GetError()); return; } }
putpixel(screen, x, y, yellow);
if ( SDL_MUSTLOCK(screen) ) { SDL_UnlockSurface(screen); } /* Update just the part of the display that we've changed */ SDL_UpdateRect(screen, x, y, 1, 1);
return;
}
To get the yellow color, the SDL_MapRGB() has to be used. The SDL_PixelFormat is the first parameter. It stores surface format information. The next three parameters correspond to the red, blue and green components of the color. The return value is the actual color corresponding to the passed color components in hexadecimal format, as follows:
Once the color has been retrieved, the next step is to get the required x and y coordinates, which is achieved by the following statement:
x = screen->w / 2; y = screen->h / 2;
then the screen surface is locked. If this is not done, then corruption of the SDL_Surface structure could happen, causing instability of the game as putpixel works on the address of the pixel directly. This is done by:
SDL_MUSTLOCK(screen);
The next step is to call the putpixel. Once putpixel has returned, then unlock the surface and update the surface. That completes placing a pixel directly onto the surface. The next section will focus on event handling with reference to the keyboard.