Search code examples
cstty

programming a simple game in c


So far, I have made a simple map (made out of characters in my terminal) and I'm trying to get an 'O' to move around in it. I find it annoying that every time I want to move I must press Enter. I found the stty command and I would like to check what the current state is, set it to raw, and when I'm done return it to it's previous state. If someone knows a better way, I'd love to hear it. I am using Ubuntu.

EDIT: Here's what i made:

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

I am a beginner.


Solution

  • If you want to do it with a program, under Unix systems you can use termios functions (tcsetattr and tcgetattr). As suggested, ncurses library can do most of the painful job for you : set terminal attributes and draw on screen.