程序不会在 getch() 处暂停

Program won't pause at getch()

我正在为类 roguelike 游戏编写代码,这部分代码使用 getch() 获取用户输入以指导角色下一步移动到哪里。我的理解是 getch() 将暂停程序,直到它收到用户的输入,但我的代码在到达该行时不会暂停。这是代码

uint32_t pc_next_pos(dungeon *d)
  {
    char comm;
    comm = getch();
    command_move(d, comm);
  }

整个程序编译正确,只是它没有暂停程序让我移动我的角色,而是继续运行直到游戏中所有怪物死亡后程序终止。该代码未包含在内,因为它在此方法中不起作用。

我是不是在这个不允许 getch() 暂停程序的方法中做错了什么,还是我误解了 getch() 的作用?

您可以更改 getch 函数行为调用 timeout:

对于 man 3 超时:

The timeout and wtimeout routines set blocking or non-blocking read for a given window. If delay is negative, blocking read is used (i.e., waits indefinitely for input). If delay is zero, then non-blocking read is used (i.e., read returns ERR if no input is waiting). If delay is positive, then read blocks for delay milliseconds, and returns ERR if there is still no input. Hence, these routines provide the same functionality as nodelay, plus the additional capability of being able to block for only delay milliseconds (where delay is positive).

uint32_t pc_next_pos(dungeon *d)
  {
    char comm;
    /* set getch blocking */
    timeout(-1);
    comm = getch();
    command_move(d, comm);
    return ....
  }

getch() 可以是阻塞的或非阻塞的(甚至是超时阻塞),具体取决于输入选项。你想要阻止;你变得无阻塞。问题不在这里,在这个函数中,而是在你的 curses 初始化代码中的某个地方(未显示)——你可能在 initscr()。如果没有,您可能需要添加类似 nodelay(stdscr, FALSE) 的内容,尽管这应该是默认行为。

您还应该阅读 halfdelay()cbreak()(通常与 nodelay()timeout() 在同一手册页上)。