Clearing the screen

int phpSDL_MapRGB ( array format, int red, int green, int blue)

int phpSDL_FillRect ( array destination, array destination_rectangle, int color)

Clearing the game screen is a problem easily solved using two new functions: phpSDL_MapRGB(), and phpSDL_FillRect(). The first is a generic function that takes four parameters and returns a colour you can use in various other functions. These four parameters are a screen format, and a red, green, and blue amount from 0 to 255. The screen format is the "format" element from the surface you are generating the colour for. As we want to draw this rectangle onto the main display surface, we use $video, as returned by phpSDL_SetVideoMode(). You can change the red, green, and blue (RGB) values all you like to get the exact colour you are after. For example:

$red = phpSDL_MapRGB($video['format'], 255, 0, 0);
$green = phpSDL_MapRGB($video['format'], 0, 255, 0);
$blue = phpSDL_MapRGB($video['format'], 0, 0, 255);
$purple = phpSDL_MapRGB($video['format'], 255, 0, 255);
$white = phpSDL_MapRGB($video['format'], 255, 255, 255);

Of course, what we're interested in is black, as we want to fill in with black the places the square has been to, so add this line before the line $done = false;:

$black = phpSDL_MapRGB($video['format'], 0, 0, 0);

Now, phpSDL_FillRect() is designed to draw a filled rectangle on a surface in a given colour. We're going to use this to draw a black rectangle on our screen that is the size of the whole screen, effectively blanking it, and we're going to do this as the start of every frame.

So, before the call to $event = array();, add this line:

phpSDL_FillRect($video, array("x"=>0,"y"=>0,"w"=>640,"h"=>480), $black);

Now, to explain what those parameters do. The first parameter, $video, is the surface on which we want to draw our rectangle. The last parameter, $black, is the colour to use for drawing. The middle parameter, the definition of an array with X and Y as 0, Y as 640, and H as 480, is the size and position of the rectangle. As our window is 640x480, this draws our rectangle over the whole screen as planned. If you want to up the performance a little, create the array outside of the loop and store it in $screensize or something, then use that for parameter two instead of recreating the loop each time.

Note that technically we do not have to clear the whole screen - as we only have one object right now, it is faster to simply clear the area around the object. However, as you may want to have many other objects on screen later on, it is best to just clear the whole screen and save yourself the hassle.

 

Next chapter: Last tweaks >>

Previous chapter: Moving our sprite

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar