猜随机数游戏

Guess the random number game

本文关键字:游戏 随机数      更新时间:2023-10-16

我正在制作一个猜数字游戏,我不知道如何结合一定数量的猜测,用户必须得到正确的答案。我希望用户只有 3 次猜测来猜测数字,但在 3 次猜测之后,如果他们没有得到正确的,他们就会输。这是我下面的代码:

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand ( time(NULL) );
cout << "Select a difficulty: 1) Easy, 2) Medium, 3) Hard " << endl;
int userlevel;
int userinput;
int randomNumber;
cin >> userlevel;
{
if (userlevel==1)
  cout << "You chose Easy: 3 chances to guess correctly" << endl;
  cout << "Pick a number between 1 and 10: " << endl;
  cin >> userinput;
  randomNumber = rand() % 10 + 1;
  if (randomNumber==userinput)
    cout << "You, guessed correctly! You win!" << endl;
  else
    cout << "I'm sorry, that is not correct. You lose." << endl;
}

{
  if (userlevel==2)
   cout << "You chose Medium: 4 chanaces to guess correctly" << endl;
   cout << "Pick a number between 1 and 50: " << endl;
     cin >> userinput;
     randomNumber = rand() % 50 + 1;
   if (randomNumber==userinput)
     cout << "You, guessed correctly! You win!" << endl;
   else
    cout << "I'm sorry, that is not correct. You lose." << endl;
  }

   {
    if (userlevel==3)
     cout << "You chose Hard: 5 chances to guess correctly" << endl;
     cout << "Pick a number between 1 and 100: " << endl;
     cin >> userinput;
     randomNumber = rand() % 100 + 1;
  if (randomNumber==userinput)
       cout << "You, guessed correctly! You win!" << endl;
     else
       cout << "I'm sorry, that is not correct. You lose." << endl;
 }
  return 0;
 }

你应该研究一下while循环。它将像这样使用:

    int main() {
    //...everything above this in yours is good
    int Number_to_guess = (rand() % 10 + 1);
    int NChances = userlevel + 2;
    cout << "You have " << NChances << " chances to guess right.n";
    while (NChances != 0)
    {
        cout << "Guess: ";
        cin >> userinput;
        if (userinput == Number_to_Guess) {
            cout << "You win! Congrats!n";
            break; // this will break out of the while-loop
        }
        NChances--; // this will count down the chances left
    }
    if (NChances == 0) {
        cout << "Sorry, you lose. Try again next time!n";
    }
    return 0;
    }

你在这里缺少的主要想法是围绕猜测限制的循环。因此,在弄清楚它们是什么级别之后,您可以说出类似于以下伪代码的内容:

While (counter <= 3)
*Your If Statements*
counter = counter +1

确保在他们猜对数字的 if 语句中,尽早将它们从循环中解脱出来。

最后,在进入循环之前猜测一个数字可能更有意义。所以,就像他们选择难度一样,根据他们说的话选择随机数,然后循环开始。现在的方式是,每次通过循环都会创建一个新的随机数。我不确定这是否是有意的。