Tutorial SDL - Timers
Timers (ou temporizadores) é um importante conteito em jogos, pois a toda hora é preciso contar o tempo, seja para passar de fase, ou para acontecer alguma ação.A aplicação fará o seguinte: começa a contar os segundos, caso o usuário aperte S ele parará, quando apertar novamente começa de novo. Nesse Tutorial vamos usar a função SDL_GetTicks() para pegar o timestamp.
Agora vamos ao nosso código:
-
//O Cabeçalho
-
#include "SDL/SDL.h"
-
#include "SDL/SDL_image.h"
-
#include "SDL/SDL_ttf.h"
-
#include <string>
-
#include <sstream>
-
-
//Atributos da Tela
-
const int SCREEN_WIDTH = 640;
-
const int SCREEN_HEIGHT = 480;
-
const int SCREEN_BPP = 32;
-
-
//As superfícies
-
SDL_Surface *imagem = NULL;
-
SDL_Surface *tela = NULL;
-
SDL_Surface *mensagem = NULL;
-
SDL_Surface *segundos = NULL;
-
-
//A estrutura que usaremos para capturarmos os eventos
-
SDL_Event evento;
-
-
//A fonte que será usada
-
TTF_Font *fonte = NULL;
-
-
//A cor da fonte
-
SDL_Color cor = { 255, 255, 255 };</sstream></string>
Inserimos o sstream para a conversão de string em int (mais a frente) e incluí mais uma superfície chamada segundos
-
bool inicia()
-
{
-
//Inicia os subsistemas da SDL
-
if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
-
{
-
return false;
-
}
-
-
//Setando a tela
-
tela = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
-
-
//Verifica se existe algum erro na tela
-
if( tela == NULL )
-
{
-
return false;
-
}
-
-
//Iniciando SDL_ttf
-
if( TTF_Init() == -1 )
-
{
-
return false;
-
}
-
-
//Setando o caption da janela
-
SDL_WM_SetCaption( "Tutorial SDL - Timers", NULL );
-
-
//Se tudo deu certo
-
return true;
-
}
-
-
bool carrega_arquivos(std::string arquivo)
-
{
-
//Carrega a imagem
-
imagem = carregaImagem( arquivo.c_str() );
-
-
//Verifica se existe algum erro no carregamento da imagem
-
if( imagem == NULL )
-
{
-
return false;
-
}
-
-
//Carrega a fonte
-
fonte = TTF_OpenFont( "trebuc.ttf", 30 );
-
-
//Se existir algum problema com a fonte
-
if( fonte == NULL )
-
{
-
return false;
-
}
-
-
//se tudo der certo
-
return true;
-
}
-
-
void limpa()
-
{
-
//Libera a imagem
-
SDL_FreeSurface( imagem );
-
SDL_FreeSurface( mensagem );
-
-
}
-
-
void sair()
-
{
-
//Fecha a SDL_ttf
-
TTF_Quit();
-
-
//Fecha a SDL
-
SDL_Quit();
-
}
Até aqui, tudo igual aos outros tutoriais, agora vamos ao main():
-
int main( int argc, char* args[] )
-
{
-
-
//Variável necessária para saber se o usuário fechou a janela
-
bool quit = false;
-
-
//O nosso timer
-
Uint32 inicio = 0;
-
-
//A variavel para ver se o timer esta ou nao ativo
-
bool correndo = true;
-
-
//Começa o timer
-
inicio = SDL_GetTicks();
-
-
//Inicia
-
if( inicia() == false )
-
{
-
return 1;
-
}
-
-
//Carrega os arquivos
-
if( carrega_arquivos("fundo.jpg") == false )
-
{
-
return 1;
-
}
-
-
//Carrega o texto na mensagem
-
mensagem = TTF_RenderText_Solid( fonte, "CubaGames - Tutorial SDL", cor );
-
-
//Aplicando as superfícies na tela
-
aplicaSuperficie( 0, 0, imagem, tela );
-
aplicaSuperficie( 100, 200, mensagem, tela );
-
-
//Atualiza a tela
-
if( SDL_Flip( tela ) == -1 )
-
{
-
return 1;
-
}
-
-
//Enquanto o usuário não fechar o programa
-
while( quit == false )
-
{
-
//Quando ocorrer um evento
-
while( SDL_PollEvent( &evento ) )
-
{
-
//Busca por um evento do usuário
-
while( SDL_PollEvent( &evento ) )
-
{
-
//Se um botao foi pressionado
-
if( evento.type == SDL_KEYDOWN )
-
{
-
//Se o "s" foi pressionado
-
if( evento.key.keysym.sym == SDLK_s )
-
{
-
//Se o temporizador estiver ativo
-
if( correndo == true )
-
{
-
//Pára o timer
-
correndo = false;
-
inicio = 0;
-
}
-
else
-
{
-
//Começa o timer
-
correndo = true;
-
inicio = SDL_GetTicks();
-
}
-
}
-
}
-
-
//Se o usuário fechou a janela
-
else if( evento.type == SDL_QUIT )
-
{
-
//Sai do programa
-
quit = true;
-
}
-
-
//Aplica o fundo
-
aplicaSuperficie( 0, 0, imagem, tela );
-
-
//Aplica a mensagem (aperte o s, bla bla bla)
-
aplicaSuperficie( ( SCREEN_WIDTH - mensagem->w ) / 2, 200, mensagem, tela );
-
-
//se o Timer estiver correndo
-
if( correndo == true )
-
{
-
//Transforma o timer em string
-
std::stringstream tempo;
-
-
//Converte o Tempo atual em String
-
tempo <<"Timer: " <<SDL_GetTicks() - inicio;
-
-
//Aplica a o texto
-
segundos = TTF_RenderText_Solid( fonte, tempo.str().c_str(), cor );
-
-
//Aplica o temporizador
-
aplicaSuperficie( ( SCREEN_WIDTH - segundos->w ) / 2, 50, segundos, tela );
-
-
//Libera a superficie dos segundos
-
SDL_FreeSurface( segundos );
-
-
}
-
-
//Da um Update na tela
-
if( SDL_Flip( tela ) == -1 )
-
{
-
return 1;
-
}
-
-
}
-
//Libera a superficie e fecha a SDL
-
limpa();
-
sair();
-
return 0;
-
}
No loop principal verificamos se o usuário clicou o "S" e paramos ou iniciamos o timer com isso, logo abaixo verificamos se o timer está ou não rodando (correndo == true), caso esteja, faz os calculos para mostrar os segundos a partir do momento do clique do S, transforma o Stringstream tempo para string e atualiza a tela constantemente.
Para mostrar esse tutorial, foi criado 1 arquivo jpg e tem um arquivo ttf para o tipo de fonte.
Para baixar o fonte clique aqui.
Alguma Dúvida? romulo@cubagames.com.br ou comentário no site!

