0

I'm pretty new to coding, so I've been making little programs while going through an online course. I'm playing around with the idea of moving the character 'X' around a small grid using the arrow keys on the keyboard.
I've managed to get it working using looping and switch statements, but the default statement keeps executing regardless of which key is pressed.
Any ideas on where I went wrong?
Here's what I got:

#include <iostream>
#include <vector>
#include<conio.h>

#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77
using namespace std;

void print_board(int v, int vn, vector <vector<char>> board);

int main()
{
    
    vector <vector<char>> board;
    board.resize(11, vector<char>(11));

    int v{ 6 };
    int vn{ 6 };
    int c = 0;

    while (1) {

        print_board(v, vn, board);
        //system("pause");
        switch (c=_getch()) {

            case KEY_UP: v--;
                break;
            
            case KEY_DOWN: v++;
                break;
            
            case KEY_LEFT: vn--;
                break;
            
            case KEY_RIGHT: vn++;
                break;
            
            default: cout << "please use the arrow key" << endl;     
                //system("pause");  
        }
    }
    return 0;
}

void print_board(int v, int vn, vector <vector<char>> board) {
    system("CLS");
    board.at(v).at(vn) = 'X';
    for (int i{ 0 }; i < 11; i++) {

        for (int j{ 0 }; j < 11; j++) {

            cout << board.at(i).at(j) << " ";
        }
        cout << endl;
    }
}

Thanks in advance.

user4581301
  • 33,082
  • 7
  • 33
  • 54
Jords
  • 3
  • 2
  • 1
    You can look here: https://stackoverflow.com/questions/10463201/getch-and-arrow-codes – Victor Padureanu Sep 25 '20 at 03:15
  • 1
    More information is good for the soul. Pop a breakpoint in there or print out the bad values of `c` to see what's happening. and see exactly what `_getch` is giving. – user4581301 Sep 25 '20 at 03:22
  • The problem is _getch(). I suggest you replace it with a better function – kesarling He-Him Sep 25 '20 at 03:26
  • 2
    @d4rk4ng31 It's not a problem with `_getch`. If I recall from my DOS days, this function returns an extra value when returning extended key codes. Probably a `0` if I were to guess. That is clearly not being handled in this program. – paddy Sep 25 '20 at 04:32

1 Answers1

1

The _getch function is documented as follows:

When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.

Perhaps you want something like this:

int ch = _getch();
int key = (ch == 0 || ch == 0xE0) ? _getch() : 0;

switch (key)
{
    // ...
}
paddy
  • 60,864
  • 6
  • 61
  • 103