So I'm trying to get a timer program to work using LazyFoo's Tutorial.
For some reason, though, my timer only works if the mouse is moving or a key is being pressed.
I downloaded the sample program from the Tutorial and it works perfectly, even though the loop is nearly identical to mine.
Could anyone tell me why does this happen?
Thanks in advance.
Code:
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include <string>
#include <sstream>
const int SW = 640;
const int SH = 480;
const int BPP = 32;
SDL_Surface * screen = NULL;
SDL_Surface * background = NULL;
SDL_Surface * text = NULL;
SDL_Event event;
TTF_Font * font = NULL;
SDL_Color tcolor = { 255 , 255 , 255 };
bool init()
{
if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
{
return false;
}
screen = SDL_SetVideoMode( SW , SH , BPP , SDL_SWSURFACE );
if( screen == NULL || TTF_Init() == -1 )
{
return false;
}
SDL_WM_SetCaption( "Timerz!" , NULL );
return true;
}
void clean()
{
SDL_FreeSurface( background );
SDL_FreeSurface( text );
TTF_CloseFont( font );
TTF_Quit();
SDL_Quit();
}
SDL_Surface * load( std::string file )
{
SDL_Surface * loaded = NULL;
SDL_Surface * optimized = NULL;
loaded = IMG_Load( file.c_str() );
if( loaded != NULL )
{
optimized = SDL_DisplayFormat( loaded );
SDL_FreeSurface( loaded );
}
return optimized;
}
bool loadf()
{
background = load( "bg.png" );
font = TTF_OpenFont( "Qarmic_sans_Abridged.ttf" , 24 );
if( background == NULL || font == NULL )
{
return false;
}
return true;
}
void apply( int x , int y , SDL_Surface * get = NULL , SDL_Surface * give = NULL )
{
SDL_Rect off;
off.x = x;
off.y = y;
SDL_BlitSurface( get , NULL , give , &off );
}
int main( int argc , char * args[] )
{
bool quit = false;
Uint32 start = 0;
bool running = true;
if( init() == false )
{
return 1;
}
if( loadf() == false )
{
return 2;
}
start = SDL_GetTicks();
while( quit == false )
{
while( SDL_PollEvent( &event ) )
{
if( event.type == SDL_KEYDOWN )
{
if( event.key.keysym.sym == SDLK_SPACE )
{
if( running == true )
{
running = false;
start = 0;
}
else
{
running = true;
start = SDL_GetTicks();
}
}
}
else if( event.type == SDL_QUIT )
{
quit = true;
}
apply( 0 , 0 , background , screen );
if( running == true )
{
std::stringstream time;
time << "Timer: " << SDL_GetTicks() - start;
text = TTF_RenderText_Solid( font , time.str().c_str() , tcolor );
apply( ( SW - text->w ) / 2 , 100 , text , screen );
SDL_FreeSurface( text );
}
if( SDL_Flip( screen ) == -1 )
{
return 3;
}
}
}
clean();
return 0;
}