Sign in to follow this  
spacekid434

Key Listeners

Recommended Posts

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

Share this post


Link to post
Share on other sites
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!

Share this post


Link to post
Share on other sites
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 ([url="http://msdn.microsoft.com/en-us/library/ms683499%28VS.85%29.aspx"]http://msdn.microsof...28VS.85%29.aspx[/url]) 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]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this