2017-03-02 77 views
-2

警告:我是編程新手!我正在嘗試爲類項目創建一個隨機信發生器遊戲。我覺得我有一個體面的開局,但我有幾點困難。隨機信發生器遊戲

該程序應該問玩家他們想玩多少遊戲(1-5)。他們每場比賽得到的最大猜測數是5,然後如果它沒有被猜出,它應該打印出正確的答案。事實上,我擁有它,以便它能夠運行正確的猜測數量,但不是遊戲,並且當所有猜測都完成時,它是正確的答案。任何幫助表示讚賞,謝謝。

#include<iostream>; 
#include<cstdlib>; 
#include<ctime>; 
using namespace std; 
int main() 
{ 
    char alphabet [27]; 
    int number_of_games; 
    char guess; 
    int x = 1; 
    srand(time(0)); 
    int n = rand() % 26 + 1; 

     cout<<"Weclome to the Letter Guessing game!\n"; 
     cout<<"You have 5 chances to guess each letter.\n \n"; 
     cout<<"How many games do you want to play?\n"; 
     cin >> number_of_games; 

     cout<<"**************************************************\n\n"; 

    while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses 

    { 
     if (number_of_games < 1) 
     { 
      cout<< "Lets play game " << number_of_games << '\n'; 
     } 
     //cout << (char)(n+97); //cheat to make sure working 
     cout<<"Enter your guess: "; 
     cin >> guess; 
     int guessValue = int(guess); 

     if (guessValue > (n+97)) 
     { 
      cout<<"The letter you are trying to guess is before " <<guess <<"\n"; 
     } 
     else if (guessValue < (n+97)) 
     { 
      cout<<"The letter you are trying to guess is after " <<guess << "\n"; 
     } 
     else if( (char)(n+97)) 
     { 
      cout << "The answer you were looking for was " << (char)(n+97) << "\n"; 
     } 
     else 
     { 
      cout<<"Your guess is correct! \n"; 
      break; 
     } 
     //if answer is not right after x tries, cout the correct answer 
     x++; 
    } 

    system("pause"); 
    return 0; 
} 

回答

0

您可以使用「嵌套循環」 - 外環遊戲,以及轉彎的內部循環。在我的示例中,我使用了for循環。

此外,無需將所有內容都轉換爲intchar爲一個整數類型,可用於就像一個號碼:

while (x <= number_of_games) //Need to get it for how many rounds, not how many guesses 
{ 
    // Select a new char (a-z) for each game 
    char n = 97 + rand() % 27; 
    cout << "Lets play game " << x << '\n'; 
    // 5 guesses 
    for (int number_of_guesses = 0; number_of_guesses < 5; number_of_guesses++) { 
     cout << "Enter your guess: "; 
     cin >> guess; 
     if (guess > n) 
     { 
      cout << "The letter you are trying to guess is before " << guess << "\n"; 
     } 
     else if (guess < n) 
     { 
      cout << "The letter you are trying to guess is after " << guess << "\n"; 
     } 
     else 
     { 
      cout << "Your guess is correct! \n"; 
      // Break out of the inner for loop, not the while 
      break; 
     } 
    } 
    x++; 
} 
+0

謝謝您的幫助!你的建議工作得很好@JohnnyMopp – Brittany