0

到目前为止,我已经制作了一张简单的地图(由终端中的字符组成),我正试图让一个“O”在其中移动。我发现每次我想移动时都必须按 Enter 键,这很烦人。我找到了 stty 命令,我想检查当前状态是什么,将其设置为原始状态,完成后将其返回到之前的状态。如果有人知道更好的方法,我很想听听。我正在使用 Ubuntu。

编辑:这是我所做的:

#include <stdio.h>
#include <stdlib.h>
#define MAX_Y 12
#define MAX_X 23

typedef enum {
  _notOk=0,
  _Ok
}_state;

typedef struct {
  int x, y;
  char map[MAX_Y][MAX_X];

}_map;

void mapPrint(_map gameState);
_state mapMove(_map* gameState);

int main()
{
  char gameMode=_Ok;
  _map gameState={
    .x=1,
    .y=1,
    .map={
    "######################",
    "#                    #",
    "#                    #",
    "#                    #",
    "#                    #",
    "#                    #",
    "#                    #",
    "#                    #",
    "#                    #",
    "#                    #",
    "#                    #",
    "######################"}
  }; 



  system ("/bin/stty raw");
  do
  {
    mapPrint(gameState);
    gameMode=mapMove(&gameState); 
  } while(gameMode);
  system ("/bin/stty cooked");

  return 0;
}

void mapPrint(_map gameState)
{
  int i, j;

  system("clear");
  for(i=0; i<MAX_Y; i++)
  {
    for(j=0; j<MAX_X; j++)
      if (i==gameState.y && j==gameState.x)
    printf("%c", '0');
      else
    printf("%c", gameState.map[i][j]);
    printf("\n");
  }

}


_state mapMove(_map* gameState)
{
  char c=getchar();

  while (c!='w' && c!='a' && c!='s' && c!='d')
  {
    printf("Pomera se sa WASD!\n");
    c=getchar();
  }


  switch(c)
  {
    case 'w': (*gameState).y--; break;
    case 'a': (*gameState).x--; break;
    case 's': (*gameState).y++; break;
    case 'd': (*gameState).x++; break;
  }

  if((*gameState).map[(*gameState).y][(*gameState).x]==' ')
    return _Ok;

  return _notOk;  
}

我是初学者。

4

1 回答 1

1

如果你想用一个程序来做,在 Unix 系统下你可以使用termios函数(tcsetattrtcgetattr)。正如建议的那样,ncurses库可以为您完成大部分痛苦的工作:设置终端属性在屏幕上绘图。

于 2015-02-19T12:45:47.633 回答