【问题标题】:get a char that does not wait for input得到一个不等待输入的字符
【发布时间】:2017-07-22 13:56:24
【问题描述】:

我正在使用 ncurses.h 为游戏构建菜单。在这一部分中,我希望屏幕上出现一个闪烁的文本,并且只有在用户按下任意键时才退出该循环。在 conio.h 中,我使用了这个(不完美):

void start()
{
    int i;

    for (i = 0; i < 10; i++)
    {
        gotoxy(32, 18 - i);
        printf("1024");
        Sleep(200);
        clrscr();
    }

    gotoxy(32, 8);
    printf("1024");
    gotoxy (35, 18);

    while (!kbhit())            

    {
        textcolor(15);          
        gotoxy (15, 15);
        printf("Press any key to continue...");

        if (kbhit() != 0)                                   

        Sleep(1000);
        textcolor(0);           
        gotoxy (15, 15);
        printf("Aperte qualquer tecla para continuar...");

        if (kbhit() != 0)
            break;

        Sleep(500);

        if (kbhit() != 0)
            break;

    }

    textcolor(15);
    fflush(stdin);
    clrscr();

}

在 ncurses.h 中,我正在尝试做同样的事情,但 getch() 似乎在等待用户输入,因此“暂停”执行。

void start()
{
    int i, ch = 0;

    for (i = 0; i < 10; i++)
    {
        attron(COLOR_PAIR(2));
        move(18 - i, 32);
        printw("1024");
        refresh();
        usleep(200 * 1000);
        clear();
        refresh();
    }

    move(18, 35);

    while (1)
    {
        if (getch() != 0)
            break;

        attron(COLOR_PAIR(2));
        move(15, 15);

        printw("Aperte qualquer tecla para continuar...");
        refresh();

        usleep(1000 * 1000);
        clear();
        refresh();
        move(15, 15);
        printw("Aperte qualquer tecla para continuar...");

        usleep(500 * 1000);

    }

    attroff(COLOR_PAIR(2));
    system("clear");

}

解决方案? 谢谢!

【问题讨论】:

    标签: input char ncurses 2d-games conio


    【解决方案1】:

    使用 ncurses(任何 curses 实现),您可以在初始化期间通过调用 cbreak 获得单字符输入(请参阅 Initialization 的手册页部分)。

    另外,我会使用napms 而不是usleep

    由于您的程序正在使用getch,预计只是轮询,您可能希望使用timeoutnodelay 并忽略getch 返回ERR 的情况。例如

    cbreak();    /* control/C will kill the program */
    timeout(10); /* 10 milliseconds is a good compromise */
    while (1)
    {
        if (getch() == ERR)
            continue;  /* ignore, timeout expired with nothing read */
    

    【讨论】:

    • 嗯,抱歉,但我不知道如何针对我的具体问题使用 timeout 或 nodelay。如果用户在 x 时间内没有按任何内容,是否会退出该循环?如果,那么我仍然想无限期地尝试进入该循环,直到用户按下某些东西...谢谢您的回答!
    • 这是我现在得到的 untik:while(1) { wattron(win, COLOR_PAIR(CONTINUE_START_ON)); mvwprintw(win, 18, 25, "Press any key to continue"); wrefresh(win); napms(1000); wattron(win, COLOR_PAIR(CONTINUE_START_OFF)); mvwprintw(win, 18, 25, "Press any key to continue"); wrefresh(win); napms(1000); timeout(10); if(getch() == ERR) break; }
    • 超时中断没有帮助,因为循环将在 1 秒后退出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 1970-01-01
    相关资源
    最近更新 更多