使用箭头键在C

时间:2019-01-09 01:32:23

标签: c cygwin

我已经做了一个我很难理解的C练习(使用Windows上的Cygwin终端)。 练习的前提有点类似于制作蛇游戏,使用键盘上的箭头键将角色(仅是符号)移动到移动目标(再次是符号)。 给我一个模板,如下所示:

#include <stdio.h>
#include <termios.h>
#include <pthread.h>
#include <stdlib.h>

#define width  40
#define height 18
#define buf_length (width*height)
#define fox_init_x (width/3*2)
#define fox_init_y ...
#define fox_init_dir ...
#define rabbit_init_x ...
#define rabbit_init_y ...
#define rabbit_init_dir ...


//---- set keyboard mode -- please copy and use this function
struct termios
tty_prepare ()
{
  struct termios tty_attr_old, tty_attr;
  tcgetattr (0, &tty_attr);
  tty_attr_old = tty_attr;
  tty_attr.c_lflag &= ~(ECHO | ICANON);
  tty_attr.c_cc[VMIN] = 1;
  tcsetattr (0, TCSAFLUSH, &tty_attr);
  return tty_attr_old;
}

//---- restore keyboard mode -- please copy and use this function
void
tty_restore (struct termios tty_attr)
{
  tcsetattr (0, TCSAFLUSH, &tty_attr);
}

//---- fox direction
char fox_dir = fox_init_dir;

//---- keyboard thread function
void
keys_thread ()
{
// Use getchar() to read the keyboard
// Each arrow key generates a sequence of 3 symbols
// the first two are always 0x1b and 0x5b
// the third is
// 0x41 -- up
// 0x42 -- down
// 0x43 -- right
// 0x44 -- left
// Update the global variable fox_dir appropriately 
}

//---- update x and y coord-s according to direction; used in main()
void
update_coord (int *x_ptr, int *y_ptr, char dir) // call by reference to x and y
{
  switch (dir)
    {
    case 'u': if (*y_ptr > 1) (*y_ptr)--; break; // *y_ptr is called "dereference",
// which is the target pointed at by the pointer
    ...
    }
}

//---- the program starts its execution from here
int
main ()
{
  ... // variable declarations and initialisation

  term_back = tty_prepare ();
  pthread_create (...); // create the keyboard thread

  while (1)
    {
      usleep (500000);

      update_coord (&fox_x, &fox_y, fox_dir);

      ... // generate the rabbit direction at random

      update_coord (&rabbit_x, &rabbit_y, rabbit_dir);

      printf ("\033[2J\033[%d;%dH@\033[%d;%dH*", fox_y, fox_x, rabbit_y, rabbit_x);
      fflush (stdout);

      if (...) break; // add the condition(s) of game termination
    }

  pthread_cancel (keys_th);
  tty_restore (term_back);

  return 0;
}

我现在已经设法用termios来包裹住自己的头来读取被按下的键,但是我不知道如何实际使用它来改变字符的方向。

任何帮助我们都感激不尽,因为我正努力在此网上找到任何信息。

0 个答案:

没有答案