C in 2048,移动问题

标签 c stdin 2048

<分区>

我正在用 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/

相关文章:

C - 如何检查用户是否已将文本文件发送到标准输入

c++ - 将 if 语句放在 main() 或内部函数中以响应用户输入是否是一种好习惯?

c - 如何优雅地snprintf?

c - memset 设置值不正确

java - 使用 BufferedInputStream 代替 Scanner 时遇到困难

c++ - 如何在 stdin 上强制使用 eof?

c - 你如何传递一个字符数组

C错误: Expected Unqualified-id Before '{' Token

algorithm - 2048游戏的最佳算法是什么?

algorithm - 游戏2048的最优算法是什么?