我正在制作一个打地鼠程序,目前我已经设置了地鼠随机出现和消失的设置;然而,当这一切发生时,我需要接受用户输入才能“打击”内鬼。有没有什么方法可以做到这一点,而无需暂停循环等待用户输入某些内容,而是让循环在扫描输入时运行?我的代码如下。
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <stdbool.h>
int main(){
// sets the mole to be initially under_ground
bool above_ground = false;
char mole_presence[1] = {0};
// keeps the mole running as long as the game is in play
while(1){
// while the mole is not above ground, wait until he randomly is
while(above_ground == false){
int r = rand() % 6;
if (r == 5){
printf("a mole has appeared, he's dancing around!\n");
mole_presence[0] = 1;
above_ground = true;
}
else{
printf("%d\n", mole_presence[0]);
sleep(1);
}
}
// while the mole is above ground, he dances until he randomly escapes
while(above_ground == true){
bool escaped = false;
// while he hasn't escaped, continue this loop
while (escaped == false){
int x = rand() % 10;
// if he randomly escapes, break out and show he is no longer above ground
if (x == 5){
printf("he disappeared!\n");
mole_presence[0] = 0;
escaped = true;
}
else{
printf("%d\n", mole_presence[0]);
sleep(1);
}
}
above_ground = false;
}
}
}
最佳答案
我在编写 Snake-xenia 类游戏时遇到了同样的问题。在Windows中,有一个名为_kbhit
的函数可以用来检查按键是否被按下。它的原型(prototype)是
int _kbhit(void)
如果按下某个键,它将返回一个非零值。否则,它返回 0。在此处了解更多信息:https://msdn.microsoft.com/en-us/library/58w7c94c.aspx
它在 Linux 上不可用,因为 Linux 中没有 conio.h
所以对于 Linux,这个答案可以提供帮助 Using kbhit() and getch() on Linux
关于c - 如何在循环时扫描输入(C 程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43196963/