我是否错误地使用了 ncurses 库中的 getch() 函数
Am I using the getch() function from the ncurses library incorrectly?
我正在使用 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。
261
与KEY_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
返回退出循环的密钥。
相关文章:
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- C++模板来检查友元函数的存在
- 递归函数计算序列中的平方和(并输出过程)
- 对RValue对象调用的LValue ref限定成员函数
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 在C++STL中是否有Polyval(Matlab函数)等价物?
- 为什么使用 "this" 指针调用派生成员函数?
- 将对象数组的引用传递给函数
- 函数调用中参数的顺序重要吗
- 函数向量_指针有不同的原型,我可以构建一个吗
- 使用不带参数的函数访问结构元素
- 为什么 getch 在按下函数或箭头键时返回三个值?
- getch() 像 dart 中的函数
- getch() 函数在输入 key 时不执行任何操作
- 我是否错误地使用了 ncurses 库中的 getch() 函数
- getch()和scanf()函数之间的区别