我正在编写一个简短的文字冒险游戏,该游戏已经准备就绪,但现在我想用主菜单做一些事情。请注意,整个游戏都是在 DOS 下进行的。
这是我想要实现的:
按以下方式创建主菜单,但使用 while 和 switch 循环。开关循环将包含具有以下选项的案例(案例 1:、案例 2:、案例 3: 等)(将在循环之上计算)
cout << "[1] Play\n";
cout << "[2] Credits\n";
cout << "[3] Exit\n";
现在,文字冒险游戏太大了,不能只放入这个循环中,因为它变得越来越难以阅读,因为嵌套。游戏本身也有循环,还有 while 和 switch 循环。我现在想做的是类似下面的事情,但我不知道该怎么做。我会用伪代码来写:
*open file game_name.cpp*
If player presses 1
Insert actual_game.cpp
Play game until over or user presses escape
else if player presses 2
Show credits
Return to main menu
else if player presses 3
Terminate the session
else
Shows the player that an invalid option has been chosen
重点是我想包含多个 .cpp 文件,而不是将所有代码放在一个文件(actual_game.cpp)中。执行此操作的最佳方法是什么?
最佳答案
这个问答跟你的很像,看看:
如果有什么不清楚的地方,请告诉我。底线是您不插入代码文件——在您编译程序后这些文件根本不存在。您调用函数来响应每个条件——这些单独的函数将依次执行相关逻辑。您需要将您的游戏组织成一组函数,其中每个函数在游戏中执行一个特定的工作(并且可能调用更专门的函数来处理您游戏中的不同位置等)
这是一个例子:
// In GameFunctions.h:
bool StartGame ();
bool ShowCredits ();
bool ExitGame ();
// Add all function definitions here or create multiple header files to hold
// groups of function definitions. Include these headers files in your CPP files.
// In GameFunctions.cpp:
#include <iostream>
#include "GameFunctions.h"
using namespace std;
int main ( int argc, const char* argv[] )
{
int nKeyPress; // this holds the key pressed by the user
bool bContinue = true;
while ( bContinue )
{
... // read a key here into nKeyPress
switch ( nKeyPress )
{
case 1:
bContinue = StartGame ();
break;
case 2:
bContinue = ShowCredits ();
break;
case 3:
bContinue = ExitGame ();
break;
}
}
}
...
bool StartGame ()
{
// initialize your game here
InitGame ();
// Show the first room of your game and start waiting for
// user input (the user making various selections in the game).
// You'll invoke other rooms from this function as you respond to
// user selections.
ShowRoom ( 1 );
return ( true );
}
bool ShowCredits ()
{
... // show credits here
return ( true );
}
bool ExitGame ()
{
// do cleanup (if you have any to do) here
return ( false );
}
您还可以将您的游戏代码分解为多个 .cpp
和 .h
文件,以将您的函数分组到逻辑组中。即使您不使用类,将所有代码放在一个 .cpp 文件中通常也不是一个好主意,除非您的游戏非常非常短。因此,您可以创建多个 .cpp 文件,例如,每个房间一个:每个 .cpp 文件将包含处理游戏中特定房间的代码。您将需要头文件中的函数定义,并且需要将所有头文件包含在您打算使用的特定 .cpp 文件中。 (不过,您不需要在每个 .cpp 中包含每个 .h - 您只需要那些包含您打算在单个 .cpp 中使用的定义的 header 。)
最后,您的游戏将由几个 .cpp 和 .h 文件组成,并具有许多功能:一些会读取用户输入,一些会在屏幕上显示消息,一些可能会跟踪用户的输入分数,有些会在玩家第一次进入房间之前初始化房间,等等。
您可能需要标准 C 或 C++ 库中的其他头文件,具体取决于您将尝试使用的标准功能。
关于c++ - 为 DOS 程序创建主菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9502342/