我正在尝试用c ++为我的学校项目创建一个基于文本的冒险游戏。我遇到的问题是我的gameover()函数需要能够转到我的begin()函数。问题是开始必须在gameover()函数之前声明,以允许它转到begin(),只有我有其他功能,也需要访问gameover(简而言之,我需要一种方式来告诉我的程序转到函数gameover()或begin(),并知道它存在并被声明。 谢谢,西蒙
void begin() {
int name;
int choice1;
system("cls");
cout << "To start your adventure, please enter your name." << endl;
cin >> name;
cin.ignore();
system("cls");
cout << "Hello " << name << " Your adventure now begins.... Who knows what's in store for you!" << endl;
system("pause");
system("cls");
cout << "You find yourself in a dark, cramp library. " << endl;
cout << "You don't know how you got here, or where you are." << endl;
cout << "Luckily there is a sword laying on the ground next to you \nand an open door in front.\n" << endl;
cout << "What will you do?" << endl;
cout << "1. Pick up the sword" << endl;
cout << "2. Walk forward through the door" << endl;
cout << "3. Use the sword to end your miserable existence!" << endl;
cin >> choice1;
cin.ignore();
system("cls");
if (choice1 == 1) {
cout << "You quickly pick up the sword and run through the door." << endl;
system("pause");
road();
}
else if (choice1 == 2) {
cout << "While you make you way to the door...." << endl;
cout << "You somehow managed to trip on the sword." << endl;
cout << "You fall on the hilt smashing your neck, and end your painfully short life. " << endl;
system("pause");
gameover();
}
else {
cout << "That wasn't an option....." << endl;
cout << "You have now broken the game. Good day Sir!!!" << endl;
}
}
void gameover() {
int choice_b;
cout << " Oops! You died.... Try Again." << endl;
cout << "\n1. Start Again!" << endl;
cout << "2. Exit" << endl;
cin >> choice_b;
cin.ignore();
system("cls");
if (choice_b == 1) {
begin();
}
else if (choice_b == 2) { std::exit; }
}
答案 0 :(得分:1)
C ++要求您在调用语句之前描述该函数。如果你要在main()的顶部添加定义,那么它的call语句将在任何地方工作,第二个选项是在调用之前声明函数。在您希望该功能可访问的地方由您决定。
基本上,如果你在头文件或主页顶部添加一些声明,那么这些函数可以在任何地方使用
#include headerfiles....
void begin(); //
void end(); // Function prototypes
int main()
{
.....
begin(); // Will work here
}
答案 1 :(得分:0)
你应该在文件的顶部(或gameover()函数上方)添加这样的函数声明:
void begin();
答案 2 :(得分:0)
添加包含fucntion begin
和gameover
声明的头文件,或者在首次使用之前添加void begin();
和void gameover()
来自行添加声明。
答案 3 :(得分:0)
解决方案是解耦gameover
和begin
函数。考虑一下:
bool continueGame = true;
void gameover()
{
//your gameover code
if (userChoosesToExit) continueGame = false;
}
void begin()
{
//your begin code
if (playerDies) gameover();
}
void controllerFunction()
{
while (continueGame)
{
begin();
}//while
}//controller
这样,在gameover
之后,程序控件将退出begin
函数,如果continueGame
仍然为true,则while循环将继续循环,begin
将为begin
又叫了一遍。这样,您还可以随时从gameover
调用controllerFunction
和{{1}}函数。这只是逻辑结构的问题。有了这个提示,你就能够提出一个比我发布的更聪明的逻辑。
答案 4 :(得分:0)
您的代码是不必要的递归:begin()
呼叫gameover()
呼叫begin()
呼叫...
最好有一个调用必要函数的外部循环,比如
int gameover()
{ // ...
// if (choice_b == 1) {
// begin();
// }
// else if (choice_b == 2) { std::exit; }
return choice_b;
}
int i = 0;
while (i != 2)
{ begin();
// ...
i = gameover();
}