Jump to content
  • Advertisement
Sign in to follow this  

Key Listeners

This topic is 2539 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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.


Share this post

Link to post
Share on other sites
Yes, you can use getch().


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

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!