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