Search code examples
c++cursor

Cursor not moving when key pressed second time


Hey I have a c++ code in visual studio 2013. I want to move the cursor up down left right. but the problem it's not moving when i press the same key second time.

Thanks in advance Here's my code

do
{
    // Get user input (non-blocking) if it exists
    WORD wKeyCode = GetKey();

    // Process input to update application state
    switch(wKeyCode)
    {
    case VK_ESCAPE:
        bExit = true;
    case VK_LEFT:
        if(X >= 0 && X < MAP_WIDTH){
            gotoxy(X - 1, Y);
        }
        break;

    case VK_RIGHT:
        if(X >= 0 && X < MAP_WIDTH){
            gotoxy(X + 1, Y);
        }
        break;
    case VK_UP:
        if(Y >= 0 && Y < MAP_HEIGHT){
            gotoxy(X, Y - 1);
        }
        break;
    case VK_DOWN:
        if(Y >= 0 && Y < MAP_HEIGHT){
            gotoxy(X, Y + 1);
        }
        break;
    case VK_SPACE:
        if(tileMap[X][Y] == WALL){
            tileMap[X][Y] = EMPTY;
        }
        else if(tileMap[X][Y] == EMPTY){
            tileMap[X][Y] = WALL;
        }
        break;
    };

and the goto function

void gotoxy(int X, int Y)
{
    COORD coord;
    coord.X = X;
    coord.Y = Y;
    SetConsoleCursorPosition(
        GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

Solution

  • You should change X and Y variables in each case the same way you pass them to qotoxy, (or just do it in gotoxy if they are global). You need to keep track of the cursor's position if you want to make relative movements.

    Example for case VK_LEFT:

    if(X >= 0 && X < MAP_WIDTH) {
        gotoxy(X - 1, Y);
        X = X - 1; // or --X;
    }
    

    A minimalistic version:

    if(X >= 0 && X < MAP_WIDTH) {
        gotoxy(--X, Y);
    }