<分区>
我正在用 C 语言制作 2048 游戏,我需要帮助。通过按 W,A,S,D 键进行移动,例如W 向上移动,S 向下移动。
但是,在每个字母之后您都必须按 enter 接受它。如何在不按 enter 的情况下使其工作?
<分区>
我正在用 C 语言制作 2048 游戏,我需要帮助。通过按 W,A,S,D 键进行移动,例如W 向上移动,S 向下移动。
但是,在每个字母之后您都必须按 enter 接受它。如何在不按 enter 的情况下使其工作?
最佳答案
c 中没有标准库函数来完成这个;相反,您将不得不使用 termios 函数来控制终端,然后在读取输入后将其重置。
我遇到了一些无需等待定界符就可以从标准输入读取输入的代码 here .
如果您在 linux 上并使用标准的 c 编译器,那么 getch() 对您来说将不容易使用。因此我已经实现了链接中的代码,您只需粘贴此代码并正常使用 getch() 函数即可。
#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;
}
关于C in 2048,移动问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43041296/