John
John

Reputation: 105

How to make text blinking without blocking the whole program in C++ Allegro?

bool running = true;

int width = al_get_display_width(display);
while (running) {

for (;;) {
    al_clear_to_color(al_map_rgb(255, 255, 255));
    al_draw_bitmap(bitmap, 0, 0, 0);
    al_draw_text(font, al_map_rgb(0, 0, 0), 760, 375, 0, "Play (Spacebar)");
    al_flip_display();
    al_rest(1.5);

    al_clear_to_color(al_map_rgb(255, 255, 255));
    al_draw_bitmap(bitmap, 0, 0, 0);
    al_flip_display();
    al_rest(0.5);
}

ALLEGRO_EVENT event;
al_wait_for_event(queue, &event);
if (event.type == ALLEGRO_EVENT_DISPLAY_CLOSE) {
    running = false;
}
}

As you can see I have this endless loop which blocks the whole program in order for the text to blink. The question is how do I do the blinking so the others things keep working like the event which follows up (it's here for the window to close, when the user clicks X)

Upvotes: 2

Views: 963

Answers (2)

flogram_dev
flogram_dev

Reputation: 42858

The best way is to check which state (blink on or off) to draw when drawing the text. This can be derived from the current time. Something like:

while (running) {
    al_clear_to_color(al_map_rgb(255, 255, 255));
    al_draw_bitmap(bitmap, 0, 0, 0);

    if (fmod(al_get_time(), 2) < 1.5) { // Show the text for 1.5 seconds every 2 seconds.
        al_draw_text(font, al_map_rgb(0, 0, 0), 760, 375, 0, "Play (Spacebar)");
    }

    al_flip_display();

    // Handle events in a non-blocking way, for example
    // using al_get_next_event (not al_wait_for_event).
}

Upvotes: 1

StPiere
StPiere

Reputation: 4253

Outside your main loop:

  1. Create timer: timer = al_create_timer(...);

  2. Create event queue: event_queue = al_create_event_queue();

  3. At the top within your main loop:

 

al_wait_for_event(event_queue, &ev);

if (ev.type == ALLEGRO_EVENT_TIMER)
{
// do your blinking stuff here
}

Upvotes: 1

Related Questions