等待输入一段时间
Wait for input for a certain time
是否有函数可以等待输入,直到达到一定的时间?我在做一款类似Snake的游戏。
我的平台是Windows。对于基于终端的游戏,你应该看看护士。
int ch;
nodelay(stdscr, TRUE);
for (;;) {
if ((ch = getch()) == ERR) {
/* user hasn't responded
...
*/
}
else {
/* user has pressed a key ch
...
*/
}
}
编辑:参见ncurses是否适用于windows?
我找到了使用conio.h的kbhit()函数的解决方案,如下所示:-
int waitSecond =10; /// number of second to wait for user input.
while(1)
{
if(kbhit())
{
char c=getch();
break;
}
sleep(1000); sleep for 1 sec ;
--waitSecond;
if(waitSecond==0) // wait complete.
break;
}
试试bioskey()
,这是一个例子:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <bios.h>
#include <ctype.h>
#define F1_Key 0x3b00
#define F2_Key 0x3c00
int handle_keyevents(){
int key = bioskey(0);
if (isalnum(key & 0xFF)){
printf("'%c' key pressedn", key);
return 0;
}
switch(key){
case F1_Key:
printf("F1 Key Pressed");
break;
case F2_Key:
printf("F2 Key Pressed");
break;
default:
printf("%#02xn", key);
break;
}
printf("n");
return 0;
}
void main(){
int key;
printf("Press F10 key to Quitn");
while(1){
key = bioskey(1);
if(key > 0){
if(handle_keyevents() < 0)
break;
}
}
}
基于@birubisht答案我做了一个函数,这是一个有点干净,并使用非弃用版本的kbhit()
和getch()
- ISO c++的_kbhit()
和_getch()
。
函数等待用户输入的秒数
函数返回: _
当用户没有输入任何字符,否则返回输入的字符。
/**
* Gets: number of seconds to wait for user input
* Returns: '_' if there was no input, otherwise returns the char inputed
**/
char waitForCharInput( int seconds ){
char c = '_'; //default return
while( seconds != 0 ) {
if( _kbhit() ) { //if there is a key in keyboard buffer
c = _getch(); //get the char
break; //we got char! No need to wait anymore...
}
Sleep(1000); //one second sleep
--seconds; //countdown a second
}
return c;
}
相关文章:
- 在做一段时间内检查字符的无限循环
- ExtTextOut 文本的持续闪烁,在一段时间后,文本将恢复为默认字体
- 对于等待以 std::future wait() 返回的函数的 CPU 使用率或检查标志在循环中休眠一段时间哪个更好?
- ::grpc::ServerReaderWriter 对象在另一个线程中一段时间后无法调用
- 一段时间后 CPU 使用率高
- 有没有办法在一段时间后将流程从流出中分离出来
- 在一段时间内更改标签文本
- 布尔函数在一段时间内不起作用
- 解决PNP在一段时间后返回坏的rvec和tvec
- 相机的旋转方向在一段时间后反转
- boost::asio::d eadline_timer 1ms 滞后一段时间
- SDL_Mixer再次播放时,从随机位置开始一段时间,然后从头开始
- 您可以在一段时间内迭代向量
- 列表STL的时间复杂性在一段时间内进行排序
- 我的开关菜单在一段时间循环中出现问题
- 如何在一段时间内更新 QLabel?
- 我可以在开关(消息)语句的同时运行一段时间吗?(C )
- 如何从一段时间返回继续
- 执行/在循环中停留一段时间,例如 1 分钟
- 等待输入一段时间