2017-11-13 2 views
0

ユーザーが特定の文章を入力するなどの入力をしたときに停止できるカウントダウンを作成する方法を知りたい。ユーザー入力でカウントダウンタイマーを停止する

私の場合、私は「サイモンが言う」ゲームのようなことをしたいと思っています。サイモンは「UP」と言っているので、2秒の時間制限内でUPをタイプする必要があります。 「UP」でないものを入力すると、カウントダウンが停止し、失敗したことが表示されます。「UP」と入力すると、カウントダウンが破られ、勝つと言います。カウントダウンがゼロになり、何も入力していないときに失敗することも通知されます。ここで

は、私がこれまでに書いたものです:

#include <iostream> 
    #include <string> 
    #include <cmath> 
    #include<windows.h> 
    using namespace std; 


int main() { 
    string answer; 
    int success = 0; 
    int counter = 0; 

    cout << "Simon says: UP" << endl; 

    for (int i = 2; i > 0; i--) { 

     cin >> answer; 
     if (answer == "UP") { 

      cout << "You win" << endl; 
      break; 

     } 
     else { 

      cout << "You lose" << endl; 

     } 

    } 

    return 0; 

} 
+0

この[C++ブック]を見てください(https://stackoverflow.com/questions/38 8242/the-definitive-c-book-guide-and-list)リストを参照してください。 – Ron

答えて

1

マルチスレッディングに入るがなければ、あなたは_kbhit()を試みることができる、_getch()との組み合わせで、ユーザー入力を読み取る非ブロック方法は、両方ともconio.h

であります
#include <iostream> 
#include <string> 
#include <chrono> 
#include <conio.h> 

int main() 
{ 

    int timeout = 2; //2 seconds 

    std::string answer, say = "UP"; 

    std::cout << "Simon says: " << say << std::endl; 
    std::cout << "You say: "; 

    // get start time point 
    std::chrono::system_clock::time_point start = std::chrono::system_clock::now(); 
    do 
    { 
     if (_kbhit()) // check user input 
     { 
      char hit = _getch(); // read user input 
      std::cout << hit; // show what was entered 

      if (hit == 13) 
       break; // user hit enter, so end it 

      answer += hit; // add char to user answer 
     } 
    } 
    while (std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now() - start).count() < timeout); 

    // check if provided answer matches 

    if (answer == say) 
     std::cout << "\nYou win!" << std::endl; 
    else 
     std::cout << "\nYou lose!" << std::endl; 

    return 0; 
} 

enter image description here

関連する問題