0

I am making 2048 game in C and I need help. Moves are made by pressing W,A,S,D keys e.g. W is for moving up, S for down.

However, after every letter you have to press enter to accept it. How can I make it work without pressing enter?

Toby Speight
  • 27,591
  • 48
  • 66
  • 103

2 Answers2

2

what you are asking for is function named kbhit() which returns true if user presses a key on the keyboard. you can use this function to get input from the use too like see

char c= ' ';
while(1){
    if(kbhit())
        c=getch();
    if(c=='q')// condition to stop the infinite loop 
        break;
}
Paul Ogilvie
  • 25,048
  • 4
  • 23
  • 41
Ali Akber Faiz
  • 117
  • 1
  • 12
  • 4
    C standard mentions no `kbhit()` function. You are using some compiler specific library function. – user694733 Mar 27 '17 at 08:33
  • my bro it is a function defined in conio.h [link](http://www.programmingsimplified.com/c/conio.h/kbhit) – Ali Akber Faiz Mar 27 '17 at 08:35
  • 2
    @AliAkberFaiz `conio.h` is a non-standard-header. It is a windows only header file which makes you answer only useful if the OP uses a windows OS. – muXXmit2X Mar 27 '17 at 08:44
2

There is no standard library function in c to accomplish this; instead you will have to use termios functions to gain control over the terminal and then reset it back after reading the input.

I came across some code to read input from stdin without waiting for a delimiter here.

If you are on linux and using a standard c compiler then getch() will not be easily available for you. Hence i have implemented the code in the link and you just need to paste this code and use the getch() function normally.

#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;
}
Community
  • 1
  • 1