21xrx.com
2024-12-22 23:34:40 Sunday
登录
文章检索 我的文章 写文章
C++编写带有详细注释的猜单词游戏
2023-07-04 17:49:44 深夜i     --     --
C++ 编写 注释 猜单词游戏

猜单词游戏是一种受人喜欢的游戏,它不仅能提升人的词汇量,更可以锻炼人的思维敏捷度。今天我用C++编写了一款带有详细注释的猜单词游戏,让大家可以跟着我的代码来学习一下。

首先,我们需要定义一个单词列表,用于存储游戏中的单词。这里我使用了一个string的向量来存储这些单词。最后,我们需要加入一个主函数,调用游戏函数。


#include<iostream>

#include<cstdlib>

#include<vector>

#include<ctime>

#include<cctype>

#include<algorithm>

using std::vector;

using std::string;

using std::cin;

using std::cout;

using std::endl;

const int MAX_WRONG = 8; // 最多错8次

vector<string>words"TEA"; // 随机选取的单词列表

int main()

{

 srand(static_cast<unsigned int>(time(0)));

 char play;

 do {

  game();

  cout << "Do you want to play again?(y/n)" << endl;

  cin >> play;

  play = tolower(play);

 } while (play == 'y');

 return 0;

}

然后,我们需要编写游戏函数。首先,我们会随机选择一个单词,并计算该单词的长度。我们还会创建一个同样长度的猜测单词,其中每个字符都会用‘-’代替。这个猜测单词就是我们稍后要猜测的。


void game()

{

 string theWord = words[rand() % words.size()]; // 从单词列表中随机选择一个单词

 int wrong = 0; // 记录猜错次数

 string soFar(theWord.size(), '-'); // 初始化猜测单词

 string used = ""; // 已经猜测过的字母

 cout << "Welcome to the guessing game. Good luck!" << endl;

 // 游戏主体循环

 while ((wrong < MAX_WRONG) && (soFar != theWord))

 {

  cout << "You have " << (MAX_WRONG - wrong) << " incorrect guesses left." << endl;

  cout << "You've used the following letters: " << used << endl;

  cout << "So far, the word is: " << soFar << endl;

  char guess;

  cout << "Enter your guess: ";

  cin >> guess;

  guess = toupper(guess); // 转换为大写字母

  while (used.find(guess) != string::npos)

  {

   cout << "You've already guessed " << guess << endl;

   cout << "Enter your guess: ";

   cin >> guess;

   guess = toupper(guess);

  }

  used += guess; // 添加已猜测过的字母

  if (theWord.find(guess) != string::npos)

  {

   cout << "That's right! " << guess << " is in the word." << endl;

   for (int i = 0; i < theWord.length(); ++i)

   {

    if (theWord[i] == guess)

    {

     soFar[i] = guess;

    }

   }

  }

  else

  {

   cout << "Sorry, " << guess << " isn't in the word." << endl;

   ++wrong;

  }

 }

 // 游戏结束

 if (wrong == MAX_WRONG)

 

  cout << "Game over! You've been hanged!" << endl;

 

 else

 

  cout << "Congratulations! You've guessed the word!" << endl;

 

 cout << "The word was " << theWord << endl;

}

如上所示,猜单词游戏很容易编写,但增加注释之后,更容易让其他人理解你的代码。通过这篇文章,你可以开始自己的编程之旅,并学习如何编写带有详细注释的程序。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复