Hi everyone! I wanted to ask you guys a question. I was referred to this website by a friend of mine and I synced this account with my Facebook. I am new to computer programming, but I understand the beginning basics of C++ (i.e. cin, cout, void, float, vector, functions, structures, and so on). I am having difficult making a Snake/Tron-like game, which is why I am going to you guys. So here is my question: How can I make it to where a piece of mine keeps moving while a key is not held down / clicked? I have tried different ways, including the do this while (movement == KEYEVENTF_KEYUP); I need some help and it would really help me if I can get this accomplished.

Thank You Guy and Gals for looking at my post and code.

Sincerely,

-- Zvjezdan Veselinovic
..
..
..

#include <iostream>
#include <string>
#include <windows.h> // resize the screen, gotoxy, delay, and so on.
#include <iomanip> // GetAsyncKeyState(), GetKeyState(), and so on.
#include <ctime>
#include <conio.h> // _getch(), _kbhit()

using namespace std;

void Up_arrow() { printf("%c", 30); }
void Down_arrow() { printf("%c", 31); }
void Right_arrow() { printf("%c", 16); }
void Left_arrow() { printf("%c", 17); }

void delay(long seconds) 
{
    clock_t time1 = clock();  // use clock time
    clock_t time2 = time1 + seconds;
    while(time1 < time2)
        time1 = clock();
    return;
}

int gotoxy(int x, int y) // used to make window
{  
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    COORD point;
    point.X = x-1;
    point.Y = y-1;     
    SetConsoleCursorPosition(hConsole, point);
    return SetConsoleCursorPosition(hConsole, point);
}

bool hasanykeybeenpressed()
{
    for (int i = 0; i < 255; ++i)
        if (GetAsyncKeyState(i))
            return true;
    return false;
}


bool my_timer(int seconds)
{
    int start_t = time(0);
    start_t %= 1000;
    int end = start_t + seconds; ++end;
    int previous = start_t;
    for(;;)
        {
            int local = time(0);
            local %= 1000;
            if (local > previous)
                {
                    previous = local;
                    int stop = time(0); stop %= 1000;
                    int check = end -stop;
                    if (check < 0)
                        return false;
                    gotoxy(6,1); cout << setw(2) << (check) << flush;
                    if (hasanykeybeenpressed())
                        return true;
                }
        }
    return false;
}

struct Player { int up_arrow, down_arrow, left_arrow, right_arrow; };

int main()
{
    Player first_player;

    gotoxy(1,1); cout << "Time: " << endl;

    srand((unsigned int)time(0));  my_timer(5);


    cout << "Press the up arrow: "; first_player.up_arrow = _getch();
    Up_arrow(); cout << endl;

    if(_kbhit()) // checks to see if a key on the keyboard was hit.
    {
        first_player.up_arrow = _getch();

        if(first_player.up_arrow == GetAsyncKeyState(VK_UP)) // checks if the up arrow is hit.
        {
            first_player.up_arrow = GetAsyncKeyState(VK_UP); // assigns the up arrow to first player's controls.
        }
    }

    cout << "Press the down arrow: "; first_player.down_arrow = _getch();
    Down_arrow(); cout << endl;

    if(_kbhit()) // checks to see if a key on the keyboard was hit.
    {
        first_player.down_arrow = _getch();

        if(first_player.down_arrow == GetAsyncKeyState(VK_DOWN)) // checks if the down arrow is hit.
        {
            first_player.down_arrow = GetAsyncKeyState(VK_DOWN); // assigns the up arrow to first player's controls.
        }
    }

    cout << "Press the left arrow: "; first_player.left_arrow = _getch();
    Left_arrow(); cout << endl;

    if(_kbhit()) // checks to see if a key on the keyboard was hit.
    {
        first_player.left_arrow = _getch();

        if(first_player.left_arrow == GetAsyncKeyState(VK_LEFT)) // checks to see if left arrow is hit.
        {
            first_player.left_arrow = GetAsyncKeyState(VK_LEFT); // assigns the left arrow to first player's controls.
        }
    }

    cout << "Press the right arrow: "; first_player.right_arrow = _getch();
    Right_arrow(); cout << endl;

    if(_kbhit()) // checks to see if a key on the keyboard was hit.
    {
        first_player.right_arrow = _getch();

        if(first_player.right_arrow == GetAsyncKeyState(VK_RIGHT)) // checks to see if right arrow is hit.
        {
            first_player.right_arrow = GetAsyncKeyState(VK_RIGHT); // // assigns the right arrow to first player's controls
        }
    }

    system("cls");
    system("mode 100,50");

    char movement;
    int x = 1, y = 1;

    gotoxy(3,35); cout << "Move your piece: "; movement = _getch();

    if(_kbhit()) // checks to see if a key on the keyboard was hit.
    {
        for(;;) // forever-loop
        {
            movement = _getch();

            if(movement == first_player.up_arrow)
            {
                y -= 1;

                if(y == 0 || y == 30) { goto end_of_program; }
                else gotoxy(x,y); Up_arrow();
            }

            if(movement == first_player.down_arrow)
            {
                y += 1;

                if(y == 0 || y == 30) { goto end_of_program; }
                else gotoxy(x,y); Down_arrow();
            }

            if(movement == first_player.left_arrow)
            {
                x -= 1;

                if(x == 0 || x == 30) { goto end_of_program; }
                else gotoxy(x,y); Left_arrow();
            }

            if(movement == first_player.right_arrow)
            {
                x += 1;

                if(x == 0 || x == 30) { goto end_of_program; }
                else gotoxy(x,y); Right_arrow();
            }

        } // end of forever loop

    } // end of _kbhit()

    end_of_program: gotoxy(3,38); system("pause");
    return 0;
}

Dani AI

Generated

As suggested, treat the current direction as state and drive movement from a timed "tick" loop instead of from a blocking key read. The loop should: (1) poll input non‑blocking and update a Direction variable only when a valid key is detected, (2) move the piece every tick according to that Direction, and (3) redraw. That makes the piece keep moving while no key is held.

An easy, minimal pattern (console, Windows) looks like this:

enum Direction { NONE, UP, DOWN, LEFT, RIGHT };

Direction dir = RIGHT;     // initial direction
int x = 10, y = 10;
const int TICK_MS = 100;

auto readArrow = []() -> Direction {
    if (!_kbhit()) return NONE;
    int c = _getch();
    if (c == 0 || c == 224) { // arrow-key prefix
        c = _getch();
        switch (c) {
            case 72: return UP;    // up
            case 80: return DOWN;  // down
            case 75: return LEFT;  // left
            case 77: return RIGHT; // right
        }
    }
    return NONE;
};

while (running) {
    Direction input = readArrow();
    if (input != NONE) {
        // ignore 180-degree reversals for snake/tron
        if (!((dir==LEFT && input==RIGHT) || (dir==RIGHT && input==LEFT)
           || (dir==UP && input==DOWN) || (dir==DOWN && input==UP)))
            dir = input;
    }

    // move every tick regardless of key state
    switch (dir) {
        case UP: --y; break;
        case DOWN: ++y; break;
        case LEFT: --x; break;
        case RIGHT: ++x; break;
        default: break;
    }

    draw(x,y);    // your drawing routine
    Sleep(TICK_MS);
}

Troubleshooting and gotchas: arrow keys produce two _getch() values (prefix + code); GetAsyncKeyState returns a bitmask (use & 0x8000 to test "is down") and should not be compared directly to a _getch() code. Avoid blocking reads inside the tick loop (no blocking _getch calls), and avoid goto for flow control — use a running flag or break. If you need precise timing, use std::chrono::steady_clock instead of Sleep. Integrate this pattern into your forever loop: poll input, update direction, then move — that will give you continuous movement without holding a key.

Recommended Answers

All 4 Replies

Basically you should keep movement state in one separate variable and only touch it when movement affecting keys have been pressed. So you move not only when key is pressed but every tick and key pushed conditions only change the movement variable.

Can you please show me what you mean?

Ok, I just re-read my code and I re-read your comment. Would that work in my forever loop??

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.