Allegro 5 executing events at a certain interval

I am making my first game in allegro 5, this is a snake game. To move the snake game, I would like to use the square grid that I made, so the snake moves at regular intervals.

How can I use timers to create an event after a certain time?

For example, I want my snake to move in a given direction every second, I know how to control it, but I do not know how to create an event that occurs at a certain interval. I am using Codeblocks IDE with Windows XP SP3

+4
source share
1 answer

Most people who create games with Allegro have used a fixed-interval system. This means that X times per second (often 60 or 100), you process the input and start the logical loop. Then, if you have time, you draw a graphics frame.

To create a timer with a mark of 60 FPS and register it in the 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 in which it is. This means that it will move 60 units per second. You can use fractional units if you need more detail.

You might want to take a look at some of the demos that come with Allegro, as they have full-featured event loops. This is too much to include in one SO response.

+6
source

Source: https://habr.com/ru/post/1432104/


All Articles