Using arrows to move an "o"

Nov 27, 2018 at 8:58pm
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!
Nov 27, 2018 at 9:10pm
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 Nov 27, 2018 at 9:11pm
Nov 27, 2018 at 10:07pm
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 Nov 27, 2018 at 10:08pm
Nov 28, 2018 at 4:00am
Yes that one worked! Thank you
Nov 28, 2018 at 4:40am
You're welcome. :-)
Topic archived. No new replies allowed.