I am a beginner at C++ and trying to code a C++ console based snake game. I was stuck when I cannot move the snake without continuously pressing a key. Now I can do by just pressing the key once but I still do not understand the function of _kbhit() which has helped me do it.
void snake_movement(){
if(_kbhit())
switch (getch())
{
case 'w':
y_cordinate--;
break;
case 'a':
x_cordinate--;
break;
case 's':
y_cordinate++;
break;
case 'd':
x_cordinate++;
break;
default:
break;
}
}
The _getch() is a blocking function. If no keypresses are available in the input buffer, it will wait for a keypress to become available in the input buffer. So your program gets stuck inside of _getch() until a key is pressed - and that's why it wouldn't "work" unless you keep the key pressed, so that _getch() can keep returning to your program. It still would get "stuck", because new keystrokes are only available at the key repeat rate. That is: in the best case, _getch() may return a few dozen times per second. But only if a key is pressed down, and if the operating system supports autorepeat for that key.
On the other hand, _kbhit() doesn't block. It returns immediately with a zero value if no keypress is available in the input buffer. Otherwise it returns a non-zero value. That indicates that a key is available, and that you can call _getch() to get it. _kbhit() returning non-zero guarantees that _getch() won't block, i.e. it won't wait but will return immediately with the result you need.
Related
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
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...
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:
http://www.jimprice.com/jim-asc.shtml#keycodes
https://brebru.com/asciicodes.html
Say me if it has help you!
I have a section of code as such:
while (true) {
if(_kbhit()) {
cout << "keypressed";
exit(1);
}
for testing purposes to get the _kbhit() section working
The program takes arrow key input using GetAsyncKeyState() and in the case that the Shift key is pressed it runs this portion of code.
If i DONT press any arrow keys before i press shift to call this portion of code, then _kbhit evaluates to false as expected.
The problem is this, if i press an arrow key before i press shift to call this portion of code, "keypressed" is output even though no keys have been pressed since calling this portion of code.
Is kbhit somehow picking up the previous arrow key strokes? Do i need to clear an input buffer or something?
I am making Pacman in C++ with the Ncurses library. I am able to move Pacman with my code, but I want to move it so that pacman keeps moving even when I am not pressing any key and when I press another direction key, it changes direction. Right now, the pacman only takes one step when I press a key. Also I have to press a key 2 or 3 times before pacman moves in that direction.
if (ch==KEY_LEFT)
{
int b,row,column;
getyx(stdscr,row,column);
int h;
do // do-whileloop to move the pacman left until it hits the wall
{
column-=1;
mvprintw(row,column,">"); //print the ">" symbol
refresh();
waitf(0.1); //this pauses the game for 0.1sec
attron(COLOR_PAIR(1));
mvprintw(row,column,">");
attroff(COLOR_PAIR(1));
refresh();
waitf(0.1);
mvprintw(row,(b),"O"); //showing the open mouth of pacman
refresh();
waitf(0.1);
attron(COLOR_PAIR(1));a
mvprintw(row,column,"O");
attroff(COLOR_PAIR(1));
h = getch();
}
while(h == KEY_LEFT);
}
right = getch();
loop to move right in an if condition
up = getch();
loop to move up in an if condition
down = getch();
oop for moving down in an if condition.
The standard solution to this is the finite-state machine. The character has six or so possible states: standing, moving up, moving right, moving down, moving left, dead. Rather than a keypress directly moving the character, the keypress should change the character's state.
In such a small application, rather than implementing an incredibly flexible finite-state machine, you may use a very simple implementation as such:
enum PlayerState {
Standing,
MovingUp,
MovingRight,
MovingDown,
MovingLeft,
Dead
};
Then, inside your game loop you can add a very simple state check which then takes the appropriate action for the frame.
switch(state) {
case Standing:
break;
case MovingUp:
player.PositionY += 1;
break;
// ...
}
The last step is to hook input, which depends on your method of retrieving input. Using callbacks, an example is:
void KeyDown(Key k) {
switch(k) {
case UpArrow:
if(state != Dead)
state = MovingUp;
break;
case RightArrow:
if(state != Dead)
state = MovingRight;
// ...
}
}
You can see why in a larger project it would be important to implement a more flexible finite-state machine, but hopefully this example has given you an easy-to-understand idea.
You need an equivalent of kbhit, ie. a non-blocking getch. Which really gives the solution, set O_NONBLOCK on the input. See an example here. Once you have this, simply loop contiguously and just check for the key hit, w/o waiting on actual key press.
Function getch is blocked until some key is pressed. If you don't want to be blocked then call _kbhit before getch too make sure that there is something in input buffer.
EDIT: Take a look at ncurses functions nodelay and cbreak. They enable asynchronous input.
I suggest you take a look at the model-view-controller model, it will help you with this problems and all the other problems that you will have if you continue your program like this.
Edit: shortcut
To move your pacman continuously you will need a separate thread to control it and make it move. Take a look at pthreads for that.
If you keep only the user input in the main run loop of your program, the problem that you have to press the keys a few times will go away too (the problem here is that the processor has to be on the getch() line when you press the key, otherwise it will not be detected.
It is pretty easy
for each direction make 4 function
and inside the function,put in the other 3 direction function which get activated by kbhit.
and put a else statement in which it keeps moving forward if you do not hit a button i.e (!kbhit());
and then put all this in a loop.
If you do this for all the direction functions you should be able to get the desirable outcome.
I have a problem that I think is caused by the wm_keyup message not being sent correctly. I believe that the same problem occurs in Minecraft when you move your character and the input will get 'stuck'. The action of the key continues after you pressed it and doesn't cease until you tap the key again. I heard that it could be an issue between windows and the keyboard but I'm not completely sure. Also, most other mainstream games don't have this problem so there must be a correct way to do it. This is what my windows procedure code looks like:
case WM_KEYDOWN:
for (list<KeyInput>::iterator t = key_inputs.begin(); t != key_inputs.end(); ++t)
(*t).PushKeyDown(ConvertKeyCode(wparam));
return 0;
case WM_KEYUP:
for (list<KeyInput>::iterator t = key_inputs.begin(); t != key_inputs.end(); ++t)
(*t).PushKeyUp(ConvertKeyCode(wparam));
return 0;
Each KeyInput object has a queue that gets filled with key inputs and is emptied as keyboard input is requested. This code is for a multithreaded game and this technique ensures that no input is missed on any thread. I am using mutual exclusion in the KeyInput objects.
I get this problem more in my game than in Minecraft and I have no idea why. I also got it before when I was doing simpler, non-multithreaded code. I don't know how to fix this.
I appreciate any help or suggestions anyone has to offer.
After looking at the documentation for the WM_KEYDOWN message I found out that the 31st bit of lparam tells whether or not the last keydown message was the same as the latest. If you use this info to ignore repeat messages, you can get rid of the problem (but you lose repeat input from the key when it is held down). Here is my code:
case WM_KEYDOWN:
{
union
{
uint lparam;
struct { uint bits:30,_30:1,_31:1; };
} lparam_data;
lparam_data.lparam = lparam;
if (!lparam_data._30)
// key was pushed
return 0;
}
In a C++ console program, I've found how to detect and arrow key on Windows, and I've found a lot of other stuff that had nothing to do with the question (despite what I thought were good search terms), but I want to know if there is a platform-independent way to detect an arrow key press. A decent second place for this would be how to detect arrow key press in unix and mac. Code fragments would be appreciated.
There's no cross platform way to do it because it's not defined by either C or C++ standards (though there may be libraries which abstract away the differences when compiled on different platforms).
I believe the library you are looking for on POSIX boxes is curses, but I've never used it myself -- I could be wrong.
Keep in mind that it's entirely possible the console program (i.e. gnome-terminal or konsole or xterm) has monopolized the use of those keys for other functions.
As Billy said, there is no standard cross-platform way to do it.
Personally I use this (game-oriented) library for all inputs, cross-platform win/linux/mac : http://sourceforge.net/projects/wgois/
You can do this cross-platform by using SDL2.
Example code:
#include <SDL2/SDL.h>
int main()
{
SDL_Event event;
SDL_PollEvent(&event);
if(event.type == SDL_KEYDOWN)
{
// Move centerpoint of rotation for one of the trees:
switch(event.key.keysym.sym)
{
case SDLK_UP:
// do something
break;
case SDLK_DOWN:
// do something
break;
case SDLK_LEFT:
// do something
break;
case SDLK_RIGHT:
// do something
break;
case SDLK_ESCAPE:
// do something
return 0;
default:
break;
}
}
return 0;
}