2017-03-02 79 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