如何在循环时扫描输入(C程序)

时间:2017-04-04 01:42:04

标签: c input concurrency

我正在做一个打鼹鼠的程序,目前我已经设定了痣随机出现和消失;然而,虽然这一切都在继续,但我需要接受用户输入才能打击"打击"鼹鼠。有没有办法在不停顿循环的情况下等待用户输入内容,而是在扫描输入时运行循环?我的代码如下。

#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;
        }

    }

}

1 个答案:

答案 0 :(得分:0)

我在编写蛇 - xenia游戏时面临同样的问题。在Windows中有一个名为_kbhit的函数,可用于检查是否按下了键。它的原型是

  

int _kbhit(void)

如果按下了某个键,它会返回非零值。否则,它返回0.阅读更多内容:https://msdn.microsoft.com/en-us/library/58w7c94c.aspx

它在Linux上不可用,因为linux中没有conio.h所以对于linux这个答案可以帮助Using kbhit() and getch() on Linux