如何在不阻塞 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;
}
}
如您所见,我有一个无限循环,它阻止了整个程序以使文本闪烁。问题是我如何进行闪烁,以便其他事情像后续事件一样继续工作
(当用户单击 X 时,window 会在此处关闭)
在你的主循环之外:
创建定时器:timer = al_create_timer(...);
创建事件队列:event_queue = al_create_event_queue();
在主循环的顶部:
al_wait_for_event(event_queue, &ev);
if (ev.type == ALLEGRO_EVENT_TIMER)
{
// do your blinking stuff here
}
最好的方法是在绘制文本时检查要绘制的状态(闪烁或关闭)。这可以从当前时间得出。类似于:
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).
}
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 时,window 会在此处关闭)
在你的主循环之外:
创建定时器:
timer = al_create_timer(...);
创建事件队列:
event_queue = al_create_event_queue();
在主循环的顶部:
al_wait_for_event(event_queue, &ev);
if (ev.type == ALLEGRO_EVENT_TIMER)
{
// do your blinking stuff here
}
最好的方法是在绘制文本时检查要绘制的状态(闪烁或关闭)。这可以从当前时间得出。类似于:
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).
}