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

标签 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;
        }

    }

}

最佳答案

我在编写 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/

相关文章:

c - 在调用返回行为方面,fork() 和 exec() 系统调用与其他系统调用有何不同?

Java 同步和在文本 Pane 中写入

java - 如何使用 try 和 catch 继续循环以获得正确的输入?

javascript - 根据动态下拉选择转到 URL

java - 指令重新排序和发生之前的关系

ruby - 我的网络服务器应该有什么样的进程和线程比例?

c - 段错误核心转储 C

c - 您如何使用 Xcode 在 OS X 上以普通用户身份调试 libpcap 代码?

在 glInterleavedArrays 之后调用 glDrawElements 不起作用

C++ : recognizing lower case as correct when its stored as upper case?