Использование клавиш со стрелками для перемещения символа в C - PullRequest
0 голосов
/ 09 января 2019

Мне дали упражнение на C (с использованием терминала Cygwin в Windows), которое я пытаюсь понять. Суть упражнения в чем-то похожа на создание игры «змея» с использованием клавиш со стрелками на клавиатуре для перемещения персонажа (просто символа) к движущейся цели (опять же просто символа). Мне дали шаблон, как показано ниже:

#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;
}

Теперь мне удалось обернуть голову, используя термин, чтобы прочитать, какая клавиша нажата, но я не понимаю, как на самом деле использовать это, чтобы изменить направление символа.

Любая помощь приветствуется, так как я изо всех сил пытаюсь найти какую-либо информацию об этом в Интернете.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...