我正在用 C 语言制作 2048 游戏,我需要帮助。移动是通过按W, A, S,D键进行的,例如W向上移动,S向下移动。
但是,在每封信之后,您都必须按下enter才能接受。我怎样才能让它在不按的情况下工作enter?
There is no standard library function in c to accomplish this; instead you will have to use termios functions to gain control over the terminal and then reset it back after reading the input.
I came across some code to read input from stdin without waiting for a delimiter here.
If you are on linux and using a standard c compiler then getch() will not be easily available for you. Hence i have implemented the code in the link and you just need to paste this code and use the getch() function normally.
#include <termios.h>
#include <stdio.h>
static struct termios old, new;
/* Initialize new terminal i/o settings */
void initTermios(int echo)
{
tcgetattr(0, &old); /* grab old terminal i/o settings */
new = old; /* make new settings same as old settings */
new.c_lflag &= ~ICANON; /* disable buffered i/o */
new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */
tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */
}
/* Restore old terminal i/o settings */
void resetTermios(void)
{
tcsetattr(0, TCSANOW, &old);
}
/* Read 1 character - echo defines echo mode */
char getch_(int echo)
{
char ch;
initTermios(echo);
ch = getchar();
resetTermios();
return ch;
}
/* Read 1 character without echo */
char getch(void)
{
return getch_(0);
}
int main()
{
int ch;
ch = getch();//just use this wherever you want to take the input
printf("%d", ch);
return 0;
}
您要的是名为 kbhit() 的函数,如果用户按下键盘上的某个键,该函数将返回 true。您也可以使用此功能从使用中获取输入,如参见
char c= ' ';
while(1){
if(kbhit())
c=getch();
if(c=='q')// condition to stop the infinite loop
break;
}