I'm trying to make a 4x4 blocks (50x50 px) with SDL Surface. Added another block (50x50 px, I wrote the variable as 'flag') that can only move within the 4x4 blocks, so I can select one of the blocks with this one. The problem is when I move it (say I move it to flag_x + 50), the previous surface (flag_x) is still there, even though I already use blit surface. It's like taking a multiple snapshots of walking person. How can I move 'flag' normally within the 4x4 blocks? Or do I use the wrong method?
Below is the code
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <string>
#include <sstream>
using namespace std;
//Screen attributes
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
const int SCREEN_BPP = 32;
//The frame rate
const int FRAMES_PER_SECOND = 20;
//The surfaces
SDL_Surface *screen = NULL;
SDL_Surface *matchbox[4][4];
SDL_Surface *flag;
....
....
....
bool load_files()
{
flag = load_image("matchbox2.png");
if( flag == NULL )
{
return false;
}
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
matchbox[i][j] = load_image("matchbox.png");
if( matchbox[i][j] == NULL )
return false;
}
}
return true;
}
void clean_up()
{
//Free the surfaces
SDL_FreeSurface( flag );
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
SDL_FreeSurface(matchbox[i][j]);
matchbox[i][j] = NULL;
}
}
//Quit SDL
SDL_Quit();
}
int main( int argc, char* args[] )
{
for(int i=0;i<4;i++){
for(int j=0;i<4;i++) {
matchbox[i][j] = NULL;
}
}
Timer fps;
bool quit = false;
//Initialize
if( init() == false )
{
return 1;
}
//Load the files
if( load_files() == false )
{
return 1;
}
int matchbox_x = 50;
int matchbox_y = 50;
int flag_x = 50;
int flag_y = 50;
//Fill the screen white
SDL_FillRect( screen, &screen->clip_rect, SDL_MapRGB( screen->format, 0xFF, 0xFF, 0xFF ) );
//Apply matchbox to the screen
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
apply_surface( matchbox_x , matchbox_y , matchbox[i][j], screen );
matchbox_x += 50;
}
matchbox_x = 50;
matchbox_y += 50;
}
//key event
while( quit == false )
{
fps.start();
//While there's events to handle
while( SDL_PollEvent( &event ) )
{
//If a key was pressed
if( event.type == SDL_KEYDOWN )
{
switch( event.key.keysym.sym )
{
case SDLK_UP: flag_y -= 50; break;
case SDLK_DOWN: flag_y += 50; break;
case SDLK_LEFT: flag_x -= 50; break;
case SDLK_RIGHT: flag_x += 50; break;
}
}
else if( event.type == SDL_QUIT )
{
quit = true;
}
}
//collision detection
if(flag_x < 50)
flag_x += 50;
if(flag_x > 200)
flag_x -= 50;
if(flag_y < 50)
flag_y += 50;
if(flag_y > 200)
flag_y -= 50;
apply_surface(flag_x, flag_y, flag, screen);
//Update the screen
if( SDL_Flip( screen ) == -1 )
{
return 1;
}
//Cap the frame rate
if( fps.get_ticks() < 1000 / FRAMES_PER_SECOND )
{
SDL_Delay( ( 1000 / FRAMES_PER_SECOND ) - fps.get_ticks() );
}
}
//Free the surfaces and quit SDL
clean_up();
return 0;
}
function examples taken from http://lazyfoo.net/SDL_tutorials/index.php