Search code examples
c++allegroallegro5

allegro 5 performing events at a certain interval


I'm making my first game in allegro 5, it's a snake game. In order to move the snake game I'd want to use a squared grid which I made, so the snake moves at regular intervals.

How can I use timers to make an event happen at a certain amount of time?

For example, I want my snake to move every second in the direction set, I know how to control him but I don't know how to create an event which happens at a certain interval. I'm using Codeblocks IDE with Windows XP SP3


Solution

  • Most people who create games with Allegro used a fixed interval timing system. This means X times per second (often 60 or 100), you process input and run a logic cycle. Then, if you have time left over, you draw a frame of graphics.

    To create a timer that ticks at 60 FPS and register it with an event queue:

    ALLEGRO_TIMER *timer = al_create_timer(1 / 60.0);
    ALLEGRO_EVENT_QUEUE *queue = al_create_event_queue();
    
    al_register_event_source(queue, al_get_timer_event_source(timer));
    

    Now somewhere in your main event loop:

    al_start_timer(timer);
    while (playingGame)
    {
      bool draw_gfx = false;
    
      do
      {
        ALLEGRO_EVENT event;
        al_wait_for_event(queue, &event);
    
        if (event.type == ALLEGRO_EVENT_TIMER)
        {
          do_logic();
          draw_gfx = true;
        }
        else if (event.type == ... )
        {
          // process keyboard input, mouse input, whatever
          // this could change the direction the snake is facing
        }
      }
      while (!al_is_event_queue_empty(queue));
    
      if (draw_gfx)
      {
        do_gfx();
        draw_gfx = false;
      }
    }
    

    So now in do_logic(), you can move your snake one unit in the direction it is facing. This means it would move 60 units per second. You can use fractional units if you need more granularity.

    You may want to take a look at some of the demos that come with Allegro, as they have full featured event loops. It's too much to include as a single SO answer.