代码:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
int main() {
std::string secretWord;
std::string guessedWord = "";
int numGuesses = 0;
int maxGuesses = 5;
bool win = false;
// 生成随机单词作为秘密单词
srand(time(0));
int randomIndex = rand() % 6;
std::string words[6] = {"apple", "banana", "orange", "grape", "pear", "pineapple"};
secretWord = words[randomIndex];
std::cout << "欢迎来到猜词游戏!" << std::endl;
std::cout << "请输入你的猜测:" << std::endl;
while (!win && numGuesses < maxGuesses) {
std::cin >> guessedWord;
numGuesses++;
// 检查猜测是否正确
if (guessedWord == secretWord) {
win = true;
std::cout << "恭喜你,你猜对了!秘密单词是:" << secretWord << std::endl;
} else {
std::cout << "很遗憾,你猜错了。" << std::endl;
std::cout << "你还有 " << maxGuesses - numGuesses << " 次机会。" << std::endl;
// 提示猜测结果
for (int i = 0; i < secretWord.length(); i++) {
if (guessedWord[i] == secretWord[i]) {
guessedWord[i] = secretWord[i];
} else if (guessedWord[i] != ' ') {
guessedWord[i] = '_';
}
}
std::cout << "当前猜测:" << guessedWord << std::endl;
std::cout << "请输入你的下一个猜测:" << std::endl;
}
}
if (!win) {
std::cout << "很遗憾,你没有猜对。秘密单词是:" << secretWord << std::endl;
}
return 0;
}