Search code examples
c++allegro

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)


Solution

  • 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).
    }