Jump to content

  • Log In with Google      Sign In   
  • Create Account


Key Listeners


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
3 replies to this topic

#1 TheCreeperLawyer   Members   -  Reputation: 117

Like
0Likes
Like

Posted 10 June 2011 - 07:57 PM

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

Sponsor:

#2 __SKYe   Members   -  Reputation: 944

Like
2Likes
Like

Posted 11 June 2011 - 12:37 AM

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!

#3 TheCreeperLawyer   Members   -  Reputation: 117

Like
0Likes
Like

Posted 11 June 2011 - 03:59 AM

Thanks Heaps.

#4 SimonForsman   Crossbones+   -  Reputation: 5761

Like
1Likes
Like

Posted 11 June 2011 - 07:16 AM

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
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)

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!




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS