Home > Blockchain >  Can I get character from keyboard without pausing a program
Can I get character from keyboard without pausing a program

Time:01-03

I'm working on a little project to improve my coding skills and I have a problem. I'm doing a console version of Flappy Bird. So i have a map which is a two-dimensional array of chars and this map have to move to the left. I am moving all elements of an array one place to the left and after that, clearing console and showing moved map. And here is problem, map has to move constantly but player have to control a bird while map is moving. I wanted to use _getch() but it pausing a program. A question is: Can i read a keyboard input without pausing program? I mean that the map will still moving and when i press for example Space in any moment the bird position will change. I'm working on Windows 10

CodePudding user response:

Even if beginners hope it to be a simple operation, inputting a single character from the keyboard is not, because in current Operating Systems, the keyboard is by default line oriented.

And peeking the keyboard (without pausing the program) is even harder. In a Windows console application, you can try to use functions from user32, for example GetAsyncKeyState if you only need to read few possible keys: you will know if the key is currently pressed and whether if was pressed since the last call to GetAsyncKeyState.

But beware: these are rather advanced system calls and I strongly advise you not to go that way if you want to improve your coding skills. IMHO you'd better learn how to code Windows GUI applications first because you will get an event loop, and peeking for events is far more common and can be used in real world applications. While I have never seen a real world console application trying to peek the keyboard. Caveat emptor...

CodePudding user response:

Including conio.h you can use this method:

#define ARROW_UP     72
#define ARROW_DOWN   80
#define ARROW_LEFT   75
#define ARROW_RIGHT  77

int main(){

    int key;

    while( true ){
        if( _kbhit() ){     // If key is typed
            key = _getch(); // Key variable get the ASCII code from _getch()
   
            switch( key ){

                case ARROW_UP:
                    //code her...
                    break;
                case ARROW_DOWN:
                    //code her...
                    break;
                case ARROW_LEFT:
                    //code her...
                    break;
                case ARROW_RIGHT:
                    //code her...
                    break;
                default:
                    //code her...
                    break;

            }
        }
    }
  
    return 0;
}

The upper code is an example, you can do this for any key of keyboard. In this sites you can find the ASCII code of keys:

Say me if it has help you!

  • Related