Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux c++ console get key state

I want to create command line game in Linux but I don't know to get the key state. I heard of getch() but that stops the program.

like image 678
user3167666 Avatar asked Mar 28 '26 22:03

user3167666


2 Answers

I spent a little while reading around. Apparently, this is a hard thing to do without the help of a library. Many people recommended the library ncurses. If you want to try to do it by yourself, you need to learn about switching terminal modes and crazy stuff like that. This thread was very informative: Non-blocking keyboard read - C/C++

like image 79
Robert Hickman Avatar answered Mar 31 '26 10:03

Robert Hickman


In this article, the author implements a cKeyboard class, which directly listens for events from /dev/event0. The class is then used as follows:

#include "keyboard.h"

cKeyboard kb;

  ...

if (kb.getKeyState(KEY_UP)) {
    // do something
}

It works perfectly for me, but I had to change event0 to event4.

like image 43
Jan Kytka Avatar answered Mar 31 '26 10:03

Jan Kytka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!