所以我有一个基本的猜猜数字游戏。在我的int main中,我具有用于播放它的三个功能。我有一个围绕这些功能的游戏循环,布尔= false。返回值设置等于我的PlayAgain函数。一切都很好,但是当您猜对了数字时,它会问您是否由于某种原因想再次玩两次。
我尝试删除其中一个在主调用函数的实例
#include <iostream>
#include <cstdlib>
#include <ctime>
#include<string>
void PrintIntro();
void PlayGame();
bool PlayAgain();
int main() {
bool bPlayAgain = false;
do {
PrintIntro();
PlayGame();
PlayAgain(); //I've tried removing this line
bPlayAgain = PlayAgain(); //Ive also played around with this one
} while (bPlayAgain);
return (0);
}
void PrintIntro()
{
std::cout << "Guess a number between 1-100, fool!\n";
}
void PlayGame()
{
srand(static_cast<unsigned int> (time(0)));
int HiddenNumber = rand();
int Number = (HiddenNumber % 100) + 1;
int Guess;
do {
std::cin >> Guess;
if (Guess > Number) {
std::cout << "You are too high bro!\n\n";
}
else if (Guess < Number) {
std::cout << "You need to get higher bro!\n\n";
}
else if (Guess = Number) {
std::cout << "You are just high enough, you win!\n\n";
}
} while (Guess != Number);
}
bool PlayAgain()
{
std::string Response = "";
std::cout << "Would you like to play again? yes or no." << std::endl;
std::getline(std::cin, Response);
std::cout << std::endl;
return (Response[0] == 'y') || (Response[0] == 'Y');
}
答案 0 :(得分:1)
这里是固定的代码。我添加了一个名为Game的新布尔函数,该函数可以玩游戏,如果玩家想重新玩游戏,则返回true。
#include <iostream>
#include <cstdlib>
#include <ctime>
#include<string>
void PrintIntro();
void PlayGame();
bool PlayAgain();
bool Game();
int main() {
bool bPlayAgain = Game();
while(bPlayAgain == true)
{
bPlayAgain = Game();
}
return (0);
}
void PrintIntro()
{
std::cout << "Guess a number between 1-100, fool!\n";
}
void PlayGame()
{
srand(static_cast<unsigned int> (time(0)));
int HiddenNumber = rand();
int Number = (HiddenNumber % 100) + 1;
int Guess;
do {
std::cin >> Guess;
if (Guess > Number) {
std::cout << "You are too high bro!\n\n";
}
else if (Guess < Number) {
std::cout << "You need to get higher bro!\n\n";
}
else if (Guess = Number) {
std::cout << "You are just high enough, you win!\n\n";
}
} while (Guess != Number);
}
bool PlayAgain()
{
char Response;
std::cout << "Would you like to play again? yes or no." << std::endl;
std::cin >> Response;
std::cout << std::endl;
return (Response == 'y') || (Response == 'Y');
}
bool Game()
{
PrintIntro();
PlayGame();
bool selection = PlayAgain();
return selection;
}