forked from samelinux/rlTutorial2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
keyboard.c
executable file
·93 lines (86 loc) · 1.99 KB
/
keyboard.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <unistd.h>
#include "keyboard.h"
//this whole file is based on
//https://www.man7.org/linux/man-pages/man3/termios.3.html
//This structur contains the initial termianl configuration
struct termios oldKeyboardFlags;
//Initialized the keyboard: clear ICANON and ECHO flags
void keyboardInit(void)
{
struct termios newKeyboardFlags;
//get terminal flags
if(tcgetattr(0,&oldKeyboardFlags)>=0)
{
tcgetattr(0,&newKeyboardFlags);
//set terminal in non canonical mode
newKeyboardFlags.c_lflag&=~ICANON;
//disable echo of input
newKeyboardFlags.c_lflag&=~ECHO;
//read block until requested character
newKeyboardFlags.c_cc[VMIN]=1;
newKeyboardFlags.c_cc[VTIME]=0;
//set terminal falgs
tcsetattr(0,TCSANOW,&newKeyboardFlags);
}
}
//Deinitialize the keyboard: set the initial terminal configuration
void keyboardDeinit(void)
{
//set the old terminal flags
tcsetattr(0,TCSADRAIN,&oldKeyboardFlags);
}
//Read a character from the keyboard [this function will wait until the player
//press a key]
char keyboardRead(void)
{
int remaining=0;
char buffer;
//read one character from stdin
read(STDIN_FILENO,&buffer,1);
//if buffer contains 27 [ESC] we may have an escape sequence
if(buffer==27)
{
//if there are more character [mybe it's just ESC!]
if(ioctl(0,FIONREAD,&remaining)==0 && remaining>0)
{
//read the [ character
read(STDIN_FILENO,&buffer,1);
if(buffer==91)
{
//read the "real" character and translate it
read(STDIN_FILENO,&buffer,1);
switch(buffer)
{
case 49:
buffer='y';
break;
case 52:
buffer='b';
break;
case 53:
buffer='u';
break;
case 54:
buffer='n';
break;
case 68://left arrow
buffer='h';
break;
case 66://down arrow
buffer='j';
break;
case 65://up arrow
buffer='k';
break;
case 67://right arrow
buffer='l';
break;
}
}
}
}
return buffer;
}