gpt4 book ai didi

c++ - 如何在 C++ 中使用 "int promptYN(string reply)"结束刽子手游戏

转载 作者:行者123 更新时间:2023-11-28 02:03:33 27 4
gpt4 key购买 nike

在我的刽子手游戏中,我无法结束游戏。使用我定义的头文件...

#define PLAY 1
#define 停止 0
#define 错误 -1

...然后我定义了函数

int promptYN(string reply)
{
reply = strToUpper(reply);
if (reply == "YES", "OK", "SURE", "Y")
return PLAY;
else if (reply == "NO", "QUIT", "STOP", "TERMINATE", "N", "Q")
return STOP;
else
return ERROR;
}

...既然函数已经在 main 中被调用,无论用户输入什么,刽子手游戏总是运行,即使我用“NO”、“QUIT”、“STOP”、“TERMINATE”、“N”回应”、“问”。

这是我用来尝试玩游戏的 while 循环,我只需要帮助确定用户何时响应“Y”,然后游戏开始,“N”然后游戏停止,或者 ERROR 和游戏重置为再次提问。谢谢你!

    cout << "Do you want to play hangman? (y or n): ";
cin >> userReply;
gameStatus = promptYN(userReply);

while (gameStatus != STOP)
{
if (gameStatus == PLAY)
{
chances = 0;
cout << "Let's Play\n\n";

guessWord = getNextWord(); // Function call (randword.h)
guessWord = strToUpper(guessWord); // Function call (MyFuncts.h)
cout << "\nWord to Guess: " << guessWord << endl;
cout << endl << h1;


while (wrong != 6) // Function to find out which hangman board to print to user
{
cout << "\nEnter a letter to guess: ";
cin >> gLetter;
gLetter = toupper(gLetter);
cout << "You entered: " << gLetter << endl << endl;

cout << gLetter << " is NOT in the word to guess.";

wrong++;

if (wrong == 0)
cout << endl << h1 << endl;
if (wrong == 1)
cout << endl << h2 << endl;
if (wrong == 2)
cout << endl << h3 << endl;
if (wrong == 3)
cout << endl << h4 << endl;
if (wrong == 4)
cout << endl << h5 << endl;
if (wrong == 5)
cout << endl << h6 << endl;
if (wrong == 6)
cout << endl << h7 << endl;
}
}

else if (gameStatus == STOP)
{
cout << "Goodbye\n";
}

else
{
cout << "Error - please enter (y or n)\n";
}
cout << "Do you want to play hangman? (y or n): ";
cin >> userReply;
gameStatus = promptYN(userReply);
}

最佳答案

这一行:

if (reply == "YES", "OK", "SURE", "Y")

不比较reply到每个字符串。为此,您必须单独比较字符串:

int promptYN(string reply)
{
if (reply == "YES" || reply =="OK" || reply == "SURE" || reply == "Y")
return PLAY;
//...
}

这会起作用,但是在 C++ 中设置它的更好方法是使用类似 std::set<std::string> 的东西并查看该值是否存在:

#include <set>
//...

int promptYN(string reply)
{
static std::set<std::string> OKResponse = {"YES", "OK", "SURE", "Y"};
static std::set<std::string> StopResponse = {"NO", "QUIT", "STOP",
"TERMINATE", "N", "Q"};
if ( OKResponse.count(reply) == 1 )
return PLAY;
else
if (StopResponse.count(reply) == 1)
return STOP;
return ERROR;
}

std::set::count将返回 1如果该值存在于集合中,否则返回 0。

要对“ok”或“stop”添加另一个响应,只需向每个 set 添加更多字符串即可值(value)观。

Live Example

注意:确保您有一个合规的 C++11编译器,均用于设置 std::set ,并确保 static以线程安全的方式工作。

关于c++ - 如何在 C++ 中使用 "int promptYN(string reply)"结束刽子手游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38425595/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com