CPP
CPP

Reputation: 13

SDL2 program stops if mouse/keys aren't pressed

I'm programming the game Snake in C, using SDL2. I'm trying to make the snake move after a period of time (500 ms or something) and I have a clock that counts the time that has passed while the program is running without fully stopping the game (instead of using SDL_Delay that does that).

This is the function:

float relogio (float segundos)
{
  clock_t start = clock();
  clock_t end = clock();
  float sec = (float)(end - start) / CLOCKS_PER_SEC ;
  sec=sec*1000+ segundos; //total time in seconds
  //printf("sec: %.02f\n", sec );

  return sec;
}

and in the main.c

if(segundos>= delay) //delay is a variable. right now is at 0.5
    {
      segundos=0;
      moves(cobra, janela);
    }

ok, so my problem is that unless my mouse is moving inside the SDL window or I'm pressing keys, the "infinite" loop (untill the variable end_game=0) stops after a period of time. I can see this in terminal because if I'm not doing anything after a while the printf that I have in the beggining of the cycle stop.

How can I make the program continue working even if I'm not doing anything in the window or pressing keys?

I hope I was clear, here is a snippet of my while loop in the main function:

while(end_game==0)
  {
    printf("ciclo\n" ); // after a while this printf stops print and restarts if I press any key or move my mouse

                               //sdl related functions                      

    segundos=relogio (segundos);

    if(segundos>= delay)
    {
      segundos=0;
      //activates function that makes snake move a block in a certain direction
    }
    SDL_RenderPresent(g_pRenderer);                                                                 
  }

EDIT

void game_end int *end_game, int mouse[])
{


  float l3 = 0.025 * LARG +120;             
  float l4 = 0.025 * LARG +200;              
  float sup = 0.2 * AC;
  float inf= 0.8 * AC;


  if(mouse[X] > l3 && mouse[X] < l4 && mouse[Y] > sup && mouse[Y] < inf)
  {
    *end_game = 1;
    game_over(); // this function quits SDL and all closes everything there is to close
  }

}                            

Upvotes: 0

Views: 353

Answers (1)

papillon
papillon

Reputation: 2062

The function you are using in order to store events, SDL_WaitEvent(), waits until an input is provided. It means that if no input is provided, the function waits for one. In other words, until you have provided an input to this function, the code that follows won't be executed.

What you want is a function that doesn't block the program. The appropriate function for doing so in SDL is SDL_PollEvent(). When no input is given, instead of waiting for one, this function returns 0.

Upvotes: 2

Related Questions