Using arrows to move an "o"

I am trying to create a snake game in C++ Microsoft Visual Studio. I have created it so that you can control where the snake moves using letters, but I would prefer it use the arrow keys. Here's the code I have for the movement of the snake so far.

void Input()
{
if (_kbhit())
{
switch (_getch())
{
case 'a':
dir = LEFT;
break;
case 'b':
dir = RIGHT;
break;
case 'c':
dir = UP;
break;
case 'd':
dir = DOWN;
break;
case 'x':
gameOver = true;
break;
}
}
}

Thanks!
the arrow keys may actually produce more than 1 character; I have forgotten exactly how they work. My advice is to write a dummy program that prints what you read back out (in hex or as integers, not chars) when you press your arrow keys, and then code around that. There may be defined constants in the win headers for the arrow keys, I don't know --- it defines a number of odd keys in there. That means you may need multiple getch calls to process the input, in a micro state machine type setup (case first letter, switch/case second letter inside type setup maybe). Youll see when you start messing with it, but treat it as if an arrow gives multiple bytes.


Last edited on
You could use virtual key codes something like this. Unfortunately I can't test it myself so I don't know if it works.
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
37
#include <iostream>
#include <cstdlib>
#include <windows.h>

WORD getKey() {
    HANDLE hin = GetStdHandle(STD_INPUT_HANDLE);
    INPUT_RECORD inrec;
    DWORD n;
    while (ReadConsoleInput(hin, &inrec, 1, &n) && n)
        if (inrec.EventType == KEY_EVENT && inrec.Event.KeyEvent.bKeyDown)
            return inrec.Event.KeyEvent.wVirtualKeyCode;
    std::cerr << "getKey failed\n";
    std::exit(EXIT_FAILURE);
    return 0;
}

int main() {
    using std::cout;
    while (true) {
        switch (getKey()) {
        case VK_LEFT:
            cout << "left\n";
            break;
        case VK_RIGHT:
            cout << "right\n";
            break;
        case VK_UP:
            cout << "up\n";
            break;
        case VK_DOWN:
            cout << "down\n";
            break;
        case VK_ESC:
            return 0;
        }
    }
}

Last edited on
Yes that one worked! Thank you
You're welcome. :-)
Topic archived. No new replies allowed.