9 tcgetattr(STDIN_FILENO, &term);
10 term.c_lflag &= ~ICANON;
11 tcsetattr(STDIN_FILENO, TCSANOW, &term);
22 bool Keyboard::read_event() {
23 ssize_t bytes_available = 0;
24 ioctl(STDIN_FILENO, FIONREAD, &bytes_available);
26 if (bytes_available) {
27 ssize_t bytes_to_read =
29 ssize_t bytes_read = ::read(STDIN_FILENO, &buf_, bytes_to_read);
31 if (bytes_read < bytes_available) {
34 unsigned char garbage[bytes_available - bytes_read];
36 ::read(STDIN_FILENO, &garbage, bytes_available - bytes_read);
37 ioctl(STDIN_FILENO, FIONREAD, &bytes_available);
38 }
while (bytes_available);
45 Key Keyboard::map_char_to_key(
unsigned char* buf) {
85 auto elapsed = system_clock::now() - last_key_poll_time_;
86 auto elapsed_ms = duration_cast<milliseconds>(elapsed).count();
90 key_pressed_ = read_event();
93 key_code_ = map_char_to_key(buf_);
98 last_key_poll_time_ = system_clock::now();
101 auto& output = observation(
prefix());
102 output(
"key_pressed") = key_pressed_;
103 output(
"up") = key_code_ ==
Key::UP;
107 output(
"w") = key_code_ ==
Key::W;
108 output(
"a") = key_code_ ==
Key::A;
109 output(
"s") = key_code_ ==
Key::S;
110 output(
"d") = key_code_ ==
Key::D;
111 output(
"x") = key_code_ ==
Key::X;
bool is_printable_ascii(unsigned char c)
constexpr unsigned char LEFT_BYTES[]
constexpr unsigned char UP_BYTES[]
constexpr unsigned char DOWN_BYTES[]
bool is_lowercase_alpha(unsigned char c)
constexpr ssize_t kMaxKeyBytes
Maximum number of bytes to encode a key.
constexpr int64_t kPollingIntervalMS
Polling interval in milliseconds.
constexpr unsigned char RIGHT_BYTES[]
Keyboard()
Constructor sets up the terminal in non-canonical mode where input is available immediately without w...
~Keyboard() override
Destructor.
std::string prefix() const noexcept final
Prefix of output in the observation dictionary.
void write(Dictionary &output) final
Write output to a dictionary.