【问题标题】:How to pause a loop in C/C++如何在 C/C++ 中暂停循环
【发布时间】:2012-03-22 02:30:18
【问题描述】:

我正在尝试为汽车游戏制作一个屏幕并让屏幕等待一个键进入下一个屏幕,问题是这段代码改变颜色的速度太快了。我已经尝试过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;
}

【问题讨论】:

  • 不知道有人还在用 Borland!
  • 如果您使用更好和更广泛使用的 api,例如 SDL 或 SFML,甚至是 Windows API,我可以为您提供帮助。
  • 很抱歉(刚刚在另一条评论中这么说)但是教授只想使用 borland C 来制作图形,而且我在 java 和 C 方面有中等经验,就像 1 个月的经验一样
  • 其他人已经回答了,谢谢您的时间,先生

标签: c++ c loops animation turbo-c


【解决方案1】:

不要使用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());

【讨论】:

    【解决方案2】:

    kbhit() 如果缓冲区中有字符,则返回true,但在返回之前不会删除该字符。到达getch() 行后,您按下的第一个键就会跳出while 循环。

    可能的解决方案:虽然它有点 hacky,但在您的 while 循环之后添加 getch() 可能会解决它。

    我还可以建议使用 ncurses 来代替那些 Borland 库吗?

    【讨论】:

    • 我们本来是要去看Open GL的,但是那个心胸狭窄的教授装作彻头彻尾的***说他会和borland C一起工作,我会试试你说的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    相关资源
    最近更新 更多