0

I'm making a whack-a-mole program, and currently I have the setup for the mole to appear and disappear at random; however, while this is all going on I'll need to accept user input in order to "whack" the mole. Is there any way to do this without pausing the loop to wait for the user to input something, and rather have the loop run WHILE scanning for input? my code is below.

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

    }

}
laroy
  • 163
  • 1
  • 1
  • 13
  • Possible duplicate, http://stackoverflow.com/questions/21091191/implementing-a-keypress-event-in-c – B. Wolf Apr 04 '17 at 01:53

1 Answers1

0

I faced the same problem while writing a snake-xenia kind of game. In Windows there is function called _kbhit which can be used to check whether the key is pressed or not. It's prototype is

int _kbhit(void)

Itreturns a nonzero value if a key has been pressed. Otherwise, it returns 0. Read more here : https://msdn.microsoft.com/en-us/library/58w7c94c.aspx

It's not available on linux as there is no conio.h in linux So for linux this answer can help Using kbhit() and getch() on Linux

Community
  • 1
  • 1
Madhusoodan P
  • 681
  • 9
  • 20