2017-04-04 2 views
0

私はモルモットプログラムを作っていますが、現在はモルが表示されランダムに消えるように設定しています。しかし、これがすべて進行している間に、私はモルを "叩く"ためにユーザー入力を受け入れる必要があります。ユーザーが何かを入力するのを待つためにループを一時停止せずに、入力をスキャンする間にループを実行させないでこれを行う方法はありますか?私のコードは以下の通りです。ルーピング中に入力をスキャンする方法(Cプログラム)

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

    } 

} 
+0

可能な重複、http://stackoverflow.com/questions/21091191/implement-a-keypress-event-in-c –

答えて

0

ゲームのヘビクセニア種類を書きながら、私は同じ問題に直面しました。 Windowsでは、_kbhitと呼ばれる機能があり、キーが押されたかどうかを確認するために使用できます。これはプロトタイプが

int _kbhit(void)

あるキーが押された場合にはゼロ以外の値をItreturnsです。そうでなければ、それはもっとここに0を読むを返します:Linuxの場合、この答えは助けることができるので、Linuxで何conio.hがないのでそれはLinux上で利用可能ではありませんhttps://msdn.microsoft.com/en-us/library/58w7c94c.aspx

Using kbhit() and getch() on Linux

関連する問題