【问题标题】:How to scan for input while looping (C Program)如何在循环时扫描输入(C 程序)
【发布时间】:2017-04-04 01:42:04
【问题描述】:

我正在制作一个打地鼠程序,目前我已经设置了地鼠随机出现和消失的设置;然而,虽然这一切都在进行,但我需要接受用户输入才能“打击”鼹鼠。有什么方法可以做到这一点,而无需暂停循环以等待用户输入内容,而是让循环在扫描输入的同时运行?我的代码如下。

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

    }

}

【问题讨论】:

标签: c input concurrency


【解决方案1】:

我在编写蛇类游戏时遇到了同样的问题。在 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多