c - 如何在 C/C++ 中暂停循环

标签 c loops animation bgi turbo-c

我正在尝试为汽车游戏制作一个屏幕并让屏幕等待按键进入下一个屏幕,问题是使用这段代码它改变颜色的速度太快了。我已经尝试过 delay()sleep(),但都没有正常工作。此外,在按下一个键后,它会关闭并且不会等待我输入一个键。我只想让标题在按下一个键之前在白色和红色之间闪烁,并了解为什么它会在按下一个键后退出。

这是我的代码:

#include <dos.h>
#include <graphics.h>
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>

int main(void)
{
    int gdriver = DETECT, gmode, errorcode;
    initgraph(&gdriver, &gmode, "C|\\BORLANDC\\BGI");
    outtextxy(250,280,"POINTER DRIVER 1.0");
    outtextxy(250,290,"LCCM 10070249");
    do
    {
        setcolor(WHITE);
        outtextxy(250,380,"PRESS ANY KEY TO CONTINUE");
        // delay(10); nothing works here :(
        setcolor(RED);
        outtextxy(250,380,"PRESS ANY KEY TO CONTINUE");
    } while(!kbhit());
    cleardevice();
    outtextxy(250,290,"HELLO"); //here it draws mega fast and then exits
    getch();
    closegraph();
    return 0;
}

最佳答案

不使用delay(10),也许可以尝试使用某种计时器变量来执行此操作。尝试类似下面的操作(对 do-while 循环的修改):

unsigned flashTimer = 0;
unsigned flashInterval = 30; // Change this to vary flash speed
do
{
    if ( flashTimer > flashInterval )
        setcolor(RED);
    else
        setcolor(WHITE);

    outtextxy(250,380,"PRESS ANY KEY TO CONTINUE");

    ++flashTimer;
    if ( flashTimer > flashInterval * 2 )
        flashTimer = 0;

    // Remember to employ any required screen-sync routine here
} while(!kbhit());

关于c - 如何在 C/C++ 中暂停循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9552747/

相关文章:

python - 避免(或加速)Python 中的大循环?

jQuery 平滑内容滑动

javascript - requestAnimationFrame 的目的是什么?重绘时间没有任何区别

c - 汇编语言是如何生成机器码的?

c - 找出递归函数的时间复杂度

c - 将动态分配的指针传递给 pthread 的正确方法是什么

ios - 在 MKMapView 上顺序绘制和显示 MKMapAnnotations

c - 如何检查一封信是否已被阅读

php - 如何迭代php文本框中的多行文本?

r - 保存 R 中 for 循环产生的对象