如何在C++ Allegro 中使文本闪烁而不会阻塞整个程序

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

本文关键字:程序 闪烁 C++ Allegro 文本      更新时间:2023-10-16
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;
}
}

如您所见,我有一个无限循环,它会阻止整个程序以使文本闪烁。问题是我如何进行闪烁,以便其他事情继续工作,就像后续事件一样(当用户单击 X 时,窗口将关闭(

最好的方法是在绘制文本时检查要绘制的状态(闪烁打开或关闭(。这可以从当前时间得出。像这样:

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

在你的主循环之外:

  1. 创建计时器:timer = al_create_timer(...);

  2. 创建事件队列:event_queue = al_create_event_queue();

  3. 在主循环的顶部:

 

al_wait_for_event(event_queue, &ev);
if (ev.type == ALLEGRO_EVENT_TIMER)
{
// do your blinking stuff here
}