I am currently writing a program in c++ that is very similar to the classic "snake" program with a开发者_运维百科 few changes. I am writing it so that it will update the screen five times a second, based on ctime, possibly more if it can be handled. One thing that I would like to do is make it so that the program has a variable in the .h file "currkeypressed." This variable will hold the key that the user is currently holding down and the snake head will go in that direction. Each node in the snake will be a separate object so the currkeypressed will only affect the head. Directional and locational data will be passed down the snake from node to node at each update.
My question is: how can I get the program to keep this data constantly, rather than updating only with a cin
when the key is pressed or at a certain interval? I know that I can accept the ascii value for the arrow keys in some sort of for loop, but that doesn't seem to work if the key is held down and if the loop is very long it can miss a press. Does anybody know how to do this?
EDIT: I am using a Linux OS, Ubuntu to be more precise
The simplest method is to use ncurse library.
However, if you prefer "raw" linux programming, you can use select
and getchar
:
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
fd_set readfs;
struct timeval timeout;
int res, key;
while (1) {
/* .. do something else .. */
FD_SET(0, &readfs); /* 0 is STDIN */
timeout.tv_usec = 10; /* milliseconds */
timeout.tv_sec = 0; /* seconds */
res = select(maxfd, &readfs, NULL, NULL, &timeout);
if (res) {
/* key pressed */
key = getchar();
if (key == 'A') { /* blar */ }
}
}
}
Once you are looking beyond simple line oriented or character orient input, you are into the details of the user input device. Each operating system has a particular mechanism for notifying a program of events like keydown and keyup.
To get an answer, add a tag for which programming environment you are in: MSWindows, Linux, Android, MacOS, etc.
You can use the library conio.h
and you can use the function _getch()
in a loop to get live input without any restriction.
#include<conio.h>
#include<iostream>
using namespace std;
int main()
{
char n='a';//Just for initialization
while(n!='e')
{
n=_getch();
}
return 0;
}
The simplest (although really not that simple) way would be to have a thread to capture the user input and then either have some kind of event driven system that can alert the head of the snake or the snake can poll for the current key.
精彩评论