[英]Am I using the getch() function from the ncurses library incorrectly?
我正在使用ncurses库在c ++中编写一个Pacman游戏,但我无法正确地移动Pacman。 我已经使用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
返回退出循环的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.