2015-10-12 3 views
-2
#include <iostream> 
#include <cstdlib> 
#include <ctime> 

using namespace std; 

int main(); 
void Menu(); 
void PlayGame(); 
void Again(); 

int main() 
{ 
// Seed the random number generator 
srand(time(0)); 
Menu(); 
return 0; 
} 

// Menu so can keep playing or close the program 
void Menu() 
{ 
int selection = 0; 
bool playing = true; 

while (playing) 
{ 
    cout << "Guess Number Game\n\n"; 
    cout << "Menu\n\n"; 
    cout << "1) Play Game\n"; 
    cout << "2) Exit\n\n"; 
    cout << "Enter your selection: "; 
    cin >> selection; 
    cin.ignore(); 
    cout << endl; 

    if (selection == 1) 
     PlayGame(); 
    else if (selection == 2) 
     playing = false; 
    else if (selection != 1 || 2) //lets the user know why they are going  back to the menu 
     cout << "Try again, choose 1 or 2" << endl; 
    } 

} 


void PlayGame() 
{ 
int RandomNumber = rand() % 50 + 1; // to set the random number between 1-50 
int attempts = 15; // sets attempts at guessing the number to 15 
int guess; 
const int HighestNum = 50; 
const int LowestNum = 1; 

cout << "Guess the random number between 1 and 50!\n"; 

while (true) 
{ 
    cout << "You have " << attempts << " attempts remaining\n\n"; // so the  user can keep track of attempts 
    cout << "Enter a number: "; 
    cin >> guess; 
    cin.ignore(); 
    cout << '\n'; 

    if (guess == RandomNumber) 
    { 
     cout << "Congratulations, you won: " << RandomNumber << "!"; 
     cout << "\n\n" << endl; 
     cout << "Would you like to play again y or n?" << endl; 
     cin.get(); 
     void Again(); 
    } 
    else if (guess < RandomNumber) // to satisfy requirements of showing user whether the guess is too low 
    { 
     cout << "That guess is too low!\n" << endl; 
    } 
    else if (guess > RandomNumber)// to satisfy requirements of showing user whether the guess is too high 
    { 
     cout << "That guess is too high!\n" << endl; 
    } 
    else if (guess > HighestNum || guess < LowestNum) 
    { 
     cout << "Guess must be lower than 50 and higher than 1, Try again"  << endl; //setup so guesses not within the range of 1-50 do not count against the 15 guesses 
     cin.get();//remove this to count guesses that are outside the 1-50 
    } 
    attempts--; 

    if (attempts == 0) 
    { 
     cout << "Sorry, no guesses remain. The random number was... " <<  RandomNumber << "!";//so the user can see the random number at the end of their attempts 
     cout << "\n"; 
     cin.get(); 
     void Again(); 
    } 
} 
void Again(); 
{ 
int decision = 0; 
bool TryAgain = true; 
char y; 
char Y; 
char n; 
char N; 

while (TryAgain) 
{ 
    cout << "Y) Play Again\n"; 
    cout << "N) Exit\n\n"; 
    cout << "Enter your selection: "; 
    cin >> decision; 
    cin.ignore(); 
    cout << endl; 

    if (decision == y || decision == Y) 
    { 
     PlayGame(); 
    } 
    else if (decision == n || decision == N) 
    { 
     TryAgain = false; 
    } 
    else if (decision != y, Y || n, N) //lets the user know why they are going back to the menu 
    { 
     cout << "Try again, choose y or n" << endl; 
    } 
} 
return 

Попытка получить void Again(); для чтения с void PlayGame();. Использование void Again(); спросить пользователя, хотят ли они снова играть. Пожалуйста помоги!C++ Guessing Game

Может также помочь кому-то помочь изменить функцию, чтобы иметь прототип int reviewGuess (int, int), где функция принимает случайное число, сгенерированное компьютером в качестве первого параметра, и число, угаданное пользователем как второе параметр.

  • Если числа совпадают, функция вернет значение, равное нулю.
  • Если число слишком велико, функция вернет значение 1.
  • Если число слишком низкое, функция вернет значение -1.

Скорее путать ATM.

Спасибо,

ответ

0

Прежде всего, вы должны исправить проблемы, о которых упоминал Альде. В следующий раз, что случилось с заявлением while (true)? Вы, вероятно, следует заменить его while (attempts != 0) и установить:

if (attempts == 0) { 
    cout << "Sorry, no guesses remain. The random number was... " << RandomNumber 
     << "!";//so the user can see the random number at the end of their attempts 
    cout << "\n"; 
    cin.get(); 
    void Again(); 
} 

выходит за рамки времени.

И о вашей int reviewGuess(int, int) функции, вы ищете что-то вроде этого:

int reviewGuess(int randomNumber,int userChoice) 
{ 
    if(randomNumber == userChoice) 
     return 0; 
    if(userChoice > 50) 
     return 1; 
    if(userChoice < 1) 
     return -1; 
} 
+0

Спасибо. Мне нужно, чтобы int reviewGuess (int, int) возвращал эти значения, затем включал оператор switch, чтобы дать ответ для каждого из значений. В принципе, возврат 0 должен был бы = «Вы выиграли !!"1 "Ваш выбор выше, чем randomNumber" -1 "Ваш выбор ниже randomNumber" – Duine

+0

я изначально сделал – Duine

+0

, но были проблемы с интеграцией Int reviewGuess (INT randomNumber, внутр userChoice) { Int х если (randomNumber == userChoice) х = 0; , если (randomNumber> userChoice) х = 1; , если (randomNumber Duine

0

Я вижу несколько вопросов:

  • вам не хватает окончание «}» в конце пустяки и снова функционирует
  • в последнем одном возвращение является обязательным и должен иметь ';' в конце
  • вы сравниваете «решение» с унифицированными переменными y, Y, n и N ... Я думаю, вы хотели сравнить его значение с символами «y», «Y», «n», «N» '
  • ' else if (decision! = Y, Y || n, N) 'не является допустимым синтаксисом, и вы уже в этом случае только с' else '
  • у вас есть дополнительный'; ' в конце 'void Again()'
  • вы пытаетесь вызвать функцию с 'void PlayGame();'
  • путь программа принимает не является чистым, и вы делаете нежелательных рекурсии, было бы лучше, чтобы вернуть значение вместо

я сделал бы что-то вроде этого:

#include <iostream> 
#include <cstdlib> 
#include <ctime> 

using namespace std; 


void PlayGame() 
{ 
    const int HighestNum = 50; 
    const int LowestNum = 1; 
    int RandomNumber = LowestNum + rand() % HighestNum; 

    cout << "Guess the random number between " << LowestNum << " and " << HighestNum << "!\n\n"; 

    int attempts = 15; 
    while (attempts > 0) 
    { 
     int guess; 
     cout << "You have " << attempts << " attempt" << (attempts > 1 ? "s" : "") << " remaining\n"; 

     cout << "Enter a number: "; 
     cin >> guess; 
     cout << endl; 

     if (guess < LowestNum || guess > HighestNum) 
     { 
      cout << "Guess must be higher than " << LowestNum << " and be lower than " << HighestNum << ". Try again!\n" << endl; 
      continue; 
     } 

     if (guess == RandomNumber) 
     { 
      cout << "Congratulations, you won!\n\n" << endl; 
      return; 
     } 
     else if (guess < RandomNumber) 
     { 
      cout << "That guess is too low!\n" << endl; 
     } 
     else if (guess > RandomNumber) 
     { 
      cout << "That guess is too high!\n" << endl; 
     } 

     --attempts; 
    } 

    cout << "Sorry, no guesses remain. The random number was... " << RandomNumber << "!\n\n"; 
} 

bool Menu() 
{ 
    cout << "Guess Number Game\n\n"; 

    cout << "Menu\n\n"; 

    cout << "1) Play Game\n"; 
    cout << "2) Exit\n\n"; 

    cout << "Enter your selection: "; 
    int selection = 0; 

    while (true) 
    { 
     cin >> selection; 
     cout << endl; 

     if (selection == 1) 
      return true; 
     else if (selection == 2) 
      return false; 
     else 
      cout << "Try again, choose 1 or 2: "; 
    } 
} 

bool Again() 
{ 
    cout << "1) Play Again\n"; 
    cout << "2) Exit\n\n"; 

    cout << "Enter your selection: "; 
    int selection = 0; 

    while (true) 
    { 
     cin >> selection; 
     cout << endl; 

     if (selection == 1) 
     { 
      return true; 
     } 
     else if (selection == 2) 
     { 
      return false; 
     } 
     else 
     { 
      cout << "Try again, choose 1 or 2: "; 
     } 
    } 
} 

int main() 
{ 
    srand(time(0)); 

    bool play = Menu(); 
    if (play) 
    while (true) 
    { 
     PlayGame(); 

     if (!Again()) 
      break; 
    } 

    return 0; 
} 
+0

Спасибо, используя настройки меню, чтобы играть снова делает намного больше смысла. Я не был уверен, могу ли я назвать функцию void в пределах пустоты. Я только начал изучать различные типы функций. Еще раз спасибо. – Duine