Key Listeners

Started by
2 comments, last by SimonForsman 12 years, 10 months ago
Hi all.

I had an idea for a basic 2D console based game in which the player moves around a small map that is represented by a 2D array. However I dont want to have to use std::cin to get the direction the player will move in.

What I was wondering is whether standard console C++ has a built in key listener. I will only be using the arrow keys and I don't need a mouse listener.

This will just help me know if this project is possible.

Thanks
Advertisement
Yes, you can use getch().


Example:

Include conio.h first, so you can use getch()
#include <conio.h>

Then declare a variable of type char:

char key;

The getch() works like the cin, except it doesn't wait to press enter after you pressed a key (besides the sintax is a little different
key = getch();

The rest, is as if you used cin, you check if the key is the one you want
if(key == <ascii code of the left arrow>)
< move left>


Hope i helped!
Thanks Heaps.
It should perhaps be noted that conio.h is not a standard C or C++ header. its not available on all platforms and compilers and the functions included in it and their names vary slightly between implementations.

conio.h is primarily included with some windows compilers for backwards compatibility with MS-DOS sourcecode , for a Windows console application the appropriate way to get keyboard input would be to use
[font="Arial"]ReadConsoleInput (it gets you a INPUT_RECORD (http://msdn.microsof...28VS.85%29.aspx) which contains the last input event)
This lets you detect things like the mouse moving, keys being released or pressed (Which means you can see if more than one key is being held down which you can't do with conio)

For Linux/Mac you'd most likely be using a curses library (like pdcurses or ncurses, raw keyboard input (set with ioctl) or x11)
[/font]
[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

This topic is closed to new replies.

Advertisement