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:

C++:
  1. //O Cabeçalho
  2. #include "SDL/SDL.h"
  3. #include "SDL/SDL_image.h"
  4. #include "SDL/SDL_ttf.h"
  5. #include <string>
  6. #include <sstream>
  7.  
  8. //Atributos da Tela
  9. const int SCREEN_WIDTH = 640;
  10. const int SCREEN_HEIGHT = 480;
  11. const int SCREEN_BPP = 32;
  12.  
  13. //As superfícies
  14. SDL_Surface *imagem = NULL;
  15. SDL_Surface *tela = NULL;
  16. SDL_Surface *mensagem = NULL;
  17. SDL_Surface *segundos = NULL;
  18.  
  19. //A estrutura que usaremos para capturarmos os eventos
  20. SDL_Event evento;
  21.  
  22. //A fonte que será usada
  23. TTF_Font *fonte = NULL;
  24.  
  25. //A cor da fonte
  26. 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

C++:
  1. bool inicia()
  2. {
  3. //Inicia os subsistemas da SDL
  4. if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
  5. {
  6. return false;
  7. }
  8.  
  9. //Setando a tela
  10. tela = SDL_SetVideoMode( SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE );
  11.  
  12. //Verifica se existe algum erro na tela
  13. if( tela == NULL )
  14. {
  15. return false;
  16. }
  17.  
  18. //Iniciando SDL_ttf
  19. if( TTF_Init() == -1 )
  20. {
  21. return false;
  22. }
  23.  
  24. //Setando o caption da janela
  25. SDL_WM_SetCaption( "Tutorial SDL - Timers", NULL );
  26.  
  27. //Se tudo deu certo
  28. return true;
  29. }
  30.  
  31. bool carrega_arquivos(std::string arquivo)
  32. {
  33. //Carrega a imagem
  34. imagem = carregaImagem( arquivo.c_str() );
  35.  
  36. //Verifica se existe algum erro no carregamento da imagem
  37. if( imagem == NULL )
  38. {
  39. return false;
  40. }
  41.  
  42. //Carrega a fonte
  43. fonte = TTF_OpenFont( "trebuc.ttf", 30 );
  44.  
  45. //Se existir algum problema com a fonte
  46. if( fonte == NULL )
  47. {
  48. return false;
  49. }
  50.  
  51. //se tudo der certo
  52. return true;
  53. }
  54.  
  55. void limpa()
  56. {
  57. //Libera a imagem
  58. SDL_FreeSurface( imagem );
  59. SDL_FreeSurface( mensagem );
  60.  
  61. }
  62.  
  63. void sair()
  64. {
  65. //Fecha a SDL_ttf
  66. TTF_Quit();
  67.  
  68. //Fecha a SDL
  69. SDL_Quit();
  70. }

Até aqui, tudo igual aos outros tutoriais, agora vamos ao main():

C++:
  1. int main( int argc, char* args[] )
  2. {
  3.  
  4. //Variável necessária para saber se o usuário fechou a janela
  5. bool quit = false;
  6.  
  7. //O nosso timer
  8. Uint32 inicio = 0;
  9.  
  10. //A variavel para ver se o timer esta ou nao ativo
  11. bool correndo = true;
  12.  
  13. //Começa o timer
  14. inicio = SDL_GetTicks();
  15.  
  16. //Inicia
  17. if( inicia() == false )
  18. {
  19. return 1;
  20. }
  21.  
  22. //Carrega os arquivos
  23. if( carrega_arquivos("fundo.jpg") == false )
  24. {
  25. return 1;
  26. }
  27.  
  28. //Carrega o texto na mensagem
  29. mensagem = TTF_RenderText_Solid( fonte, "CubaGames - Tutorial SDL", cor );
  30.  
  31. //Aplicando as superfícies na tela
  32. aplicaSuperficie( 0, 0, imagem, tela );
  33. aplicaSuperficie( 100, 200, mensagem, tela );
  34.  
  35. //Atualiza a tela
  36. if( SDL_Flip( tela ) == -1 )
  37. {
  38. return 1;
  39. }
  40.  
  41. //Enquanto o usuário não fechar o programa
  42. while( quit == false )
  43. {
  44. //Quando ocorrer um evento
  45. while( SDL_PollEvent( &amp;evento ) )
  46. {
  47. //Busca por um evento do usuário
  48. while( SDL_PollEvent( &amp;evento ) )
  49. {
  50. //Se um botao foi pressionado
  51. if( evento.type == SDL_KEYDOWN )
  52. {
  53. //Se o "s" foi pressionado
  54. if( evento.key.keysym.sym == SDLK_s )
  55. {
  56. //Se o temporizador estiver ativo
  57. if( correndo == true )
  58. {
  59. //Pára o timer
  60. correndo = false;
  61. inicio = 0;
  62. }
  63. else
  64. {
  65. //Começa o timer
  66. correndo = true;
  67. inicio = SDL_GetTicks();
  68. }
  69. }
  70. }
  71.  
  72. //Se o usuário fechou a janela
  73. else if( evento.type == SDL_QUIT )
  74. {
  75. //Sai do programa
  76. quit = true;
  77. }
  78.  
  79. //Aplica o fundo
  80. aplicaSuperficie( 0, 0, imagem, tela );
  81.  
  82. //Aplica a mensagem (aperte o s, bla bla bla)
  83. aplicaSuperficie( ( SCREEN_WIDTH - mensagem-&gt;w ) / 2, 200, mensagem, tela );
  84.  
  85. //se o Timer estiver correndo
  86. if( correndo == true )
  87. {
  88. //Transforma o timer em string
  89. std::stringstream tempo;
  90.  
  91. //Converte o Tempo atual em String
  92. tempo &lt;&lt;"Timer: " &lt;&lt;SDL_GetTicks() - inicio;
  93.  
  94. //Aplica a o texto
  95. segundos = TTF_RenderText_Solid( fonte, tempo.str().c_str(), cor );
  96.  
  97. //Aplica o temporizador
  98. aplicaSuperficie( ( SCREEN_WIDTH - segundos-&gt;w ) / 2, 50, segundos, tela );
  99.  
  100. //Libera a superficie dos segundos
  101. SDL_FreeSurface( segundos );
  102.  
  103. }
  104.  
  105. //Da um Update na tela
  106. if( SDL_Flip( tela ) == -1 )
  107. {
  108. return 1;
  109. }
  110.  
  111. }
  112. //Libera a superficie e fecha a SDL
  113. limpa();
  114. sair();
  115. return 0;
  116. }

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!