我是否错误地使用了 ncurses 库中的 getch() 函数

Am I using the getch() function from the ncurses library incorrectly?

本文关键字:getch 函数 ncurses 错误 是否      更新时间:2023-10-16

我正在使用 ncurses 库用 c++ 编写一个吃豆人游戏,但我无法正确移动吃豆人。我用getch()向上、向下、向左和向右移动它,但它只向右移动,当我按下任何其他键时不会移动到其他任何地方。

这是向上移动的代码片段。我已经编写了类似的代码,并相应地更改了一些条件,以便向左,向右和向下移动。

int ch = getch(); 
if (ch == KEY_RIGHT)
{
  int i,row,column;
  //getting position of cursor by getyx function
  for (i=column; i<=last_column; i+=2)
  {
    //time interval of 1 sec
    mvprintw(row,b,"<");   //print < in given (b,row) coordinates
    //time interval of 1 sec
    mvprintw(row,(b+1),"O");  //print "O" next to "<"
    int h = getch();   //to give the option for pressing another key 
    if (h != KEY_RIGHT)  //break current loop if another key is pressed
    {
      break;
    }
  }
}
if (condition)
{
  //code to move left
}

我用 getch() 是错了,还是我必须做其他事情?

键盘

上的许多"特殊"键 - 向上,向下,向左,向右,主页,结束,功能键等实际上将两个扫描代码从键盘控制器返回给CPU。"标准"键都返回一个。所以如果你想检查特殊键,你需要调用 getch() 两次。

例如,向上箭头首先是 224,然后是 72。

261KEY_RIGHT一致(curses.h中的八进制0405)。 这至少告诉我们,keypad被用来允许getch读取特殊键。

显示的片段没有提供它如何合并到程序其余部分的线索。 但是,在循环中使用getch可能会造成混淆,因为在退出循环时,该值将被丢弃。 如果您希望执行不同操作(与KEY_RIGHT不同),则可以使用 ungetch 在循环中保存(否则丢弃)值,例如

if (h != KEY_RIGHT)  //break current loop if another key is pressed
{
  ungetch(h);     //added
  break;
}

这样做将允许下一次调用getch返回退出循环的密钥。