0

I'm writing a game in assembly, and I need to check if a key was pressed. So, how is kbhit implemented in Linux?

Thanks.

Sason
  • 139
  • 1
  • 3
  • 6
  • 1
    It depends. Are you coding for the console? Then Paul Rs answer may be of help. Are you coding a graphical game in X11 or GL? Then you may have to look at SDL or Xevents. – Prof. Falken Oct 19 '10 at 09:19
  • Are you sure that's what you want to know? For a game, you probably want to know when a key is pressed, and when it's released. – ninjalj Oct 19 '10 at 21:41

2 Answers2

1

Google turned up a kbhit implementation for Linux in C: http://cboard.cprogramming.com/c-programming/63166-kbhit-linux.html

You could either compile this as is and call it from your assembly code, or if you really want to you could convert it to assembly.

Paul R
  • 208,748
  • 37
  • 389
  • 560
  • I know it's a noob question, but how can I use the c standard library with assembly? I mean, I don't know which files to link... – Sason Oct 19 '10 at 09:29
  • @Sason: probably the easiest thing would be to have a C main(), e.g. in main.c, which calls the entry point of your assembly program. Then you could just build something like this: `gcc -Wall main.c my_game.S other_stuff.c some_other_stuff.S -o my_game`. – Paul R Oct 19 '10 at 09:46
  • You could also open asm() tag inside the C code, i.e. `asm("jmp label")` and reference variables declared in the C code inside the asm() code. This could be very useful. – jyz Oct 19 '10 at 10:08
  • Or you could just pass -lc to the linker. – ninjalj Oct 19 '10 at 21:39
1

I assume that you want also key releases. I also assume you are on the console (for X, XKeyEvent has enough info).

First, you have to put your terminal (i.e: console) in non-canonical or in raw mode. If you don't do this, you won't see any input until there is a line delimiter or EOF on input. See my answer to your previous question.

Then, to get key releases, you want to set the keyboard to RAW or MEDIUMRAW mode (this has nothing to do with terminal raw mode, this is very Linux and console specific, see console_ioctl(4)). Don't forget to set the keyboard back to its original mode before exiting.

There's a nice article about this here.

Community
  • 1
  • 1
ninjalj
  • 42,493
  • 9
  • 106
  • 148