Open user23052036 opened 3 months ago
I will try implementing the arrow key functionality for Linux
You should use termios.h library but as I said before you Will change the terminal properties. Maybe this Will help you.
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
char getch() {
char buf = 0;
struct termios old = {0};
if (tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if (tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
if (read(0, &buf, 1) < 0)
perror("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if (tcsetattr(0, TCSADRAIN, &old) < 0)
perror("tcsetattr ~ICANON");
return buf;
}
int main() {
printf("Press a key: ");
char c = getch();
printf("\nYou pressed: %c\n", c);
return 0;
}
I have added arrow key feature in Linux. I runed in my system and it worked. If you find any bugs please report
The arrow key work properly on linux. But if you keep pressing the key for 2 3 seconds it gives you the error "You entered an invalid move. I don't know if it is possible to replicate the behaviour developed for windows OS where the process wait until the key is released. Maybe you should include something similar to may old code to avoid getting more than 1 key each time.
do
{
for (int i = 0; i < 5; i++)
key_pressed[i] = '\0';
scanf("%4s",key_pressed);
clear_input_buffer();
// Get key pressed.
if (toupper(key_pressed[0]) == 'A' || toupper(key_pressed[0]) == 'S' ||
toupper(key_pressed[0]) == 'D' || toupper(key_pressed[0]) == 'W')
*direction = key_pressed[0];
// Arrow keys are converted into ^[[A, [[B, [[C, [[C on linux. ^[ = Esc.
else if (toupper(key_pressed[0]) == 27 && toupper(key_pressed[1]) == '[') // 27 = Esc
{
switch(toupper(key_pressed[2]))
{
case 'A': *direction = 'w'; break;
case 'B': *direction = 's'; break;
case 'C': *direction = 'd'; break;
case 'D': *direction = 'a'; break;
default: *direction = 'e'; break; // no asdw no arrow key pressed.
}
}
else
*direction = 'e';
} while (*direction == 'e');
Okeii.. will check for sure.. Have you checked if it is working by pressing the key for long implementing it with this code that you send ?
I don't know who it will behave because i had to press enter after each key pressed.
In place of using ASWD keys to move around the numbers i want to use the arrow keys but i can not figure out how to do it.. If you can really solve the problem go for it. Give it a try