How to move a character with arrow keys like in Nethack?

Oct 7, 2011 at 2:04am
Hi, I'm wondering how to move a character around the console using the arrow keys, like in Nethack. This isn't a homework assignment, I'm just fooling around with text adventures in my spare time. Thanks!
Oct 7, 2011 at 2:42am
Oct 7, 2011 at 3:16am
You've got a religious hobby, Disch. Adventure games are specifically console stuff...

If you are on Windows, you'll need to use SetConsoleMode() to turn off echo and line-buffering, and ReadConsoleInput() to get the arrow keys. Here's a little example to help you get started:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iomanip>
#include <iostream>
#include <windows.h>

using std::cout;
using std::setw;

int main()
  {
  cout << "Press keys. Press 'Esc' to quit.\n";

  DWORD mode;
  HANDLE hstdin = GetStdHandle( STD_INPUT_HANDLE );
  GetConsoleMode( hstdin, &mode );
  SetConsoleMode( hstdin, 0 );

  while (true)
    {
    INPUT_RECORD ir;
    DWORD n;

    if (!ReadConsoleInputA( hstdin, &ir, 1, &n )) break;
    if (ir.EventType != KEY_EVENT) continue;
    if (!ir.Event.KeyEvent.bKeyDown) continue;

    cout << "ASCII = " << setw( 3 ) << (int)ir.Event.KeyEvent.uChar.AsciiChar
         << ", '"      <<                   ir.Event.KeyEvent.uChar.AsciiChar
         << "'; VK = " <<                   ir.Event.KeyEvent.wVirtualKeyCode
         << "\n";

    if (ir.Event.KeyEvent.uChar.AsciiChar == 27) break;
    }

  SetConsoleMode( hstdin, mode );
  return 0;
  }

You will probably also want to wait using WaitForSingleObject() to yield process time until the user presses a key. (My example doesn't do this, but you can see how to do it here: http://www.cplusplus.com/forum/beginner/5619/#msg25047 .)

If you are using *nix, you'll have to do things differently.

If you plan to use both, then I suggest you look into NCurses instead of using the OS directly.

Good luck!
Oct 7, 2011 at 3:53am
Adventure games are specifically console stuff...


Not really. Graphical ones are better.

Angband... Elona... etc

Doing it in the console when you don't have to is absurd.
Topic archived. No new replies allowed.