基于文本的游戏非分支if语句

fre*_*098 1 c++ if-statement

我正在使用C ++开发基于文本的游戏。我想知道如何在不嵌套太多if语句的情况下进入不同的事件。我在说的一个例子是...

if ( userChoice == 1 )
{
     //do something
     cout << "Pick 1 , 2, or 3" << endl;
     if ( userChoice == 1 )
     {
           cout << "pick 1, 2, 3/ some storry line" << endl;
           if ( userChoice == 3 )
           {
                cout << " storyline...123...." << endl;
                if ( userChoice == 2 )
                {
                       //etc
                }
           }
     }
}
Run Code Online (Sandbox Code Playgroud)

我如何在不分支if语句的情况下执行此概念?

Dom*_*ell 5

您可以使用数据驱动的设计来摆脱if语句的分支。

在基础上,您有一个循环,用于检查输入,然后使用当前上下文评估输入,然后更改上下文。

每个if语句都变成一个“场景”(或房间或状态,请选择一个对您正在编写的程序有意义的名称)。每个场景都有一个ID,一个描述以及一组有效的输入以及结果所代表的场景编号。

您的场景代表了结局。

您有一个循环:

loop until current scene is the end
 Print current scene description
 Ask for input
 Evaluate input
Run Code Online (Sandbox Code Playgroud)

评估输入针对当前场景的有效输入检查输入,如果有效则将当前场景设置为指定场景。

程序将当前场景初始化为第一个场景,然后开始循环。

因此,对于您的示例(显然是不完整的,但应该可以让您了解所需的数据),您将遇到以下情况:

id: 1
description: "Pick 1 , 2, or 3"
inputs: "1" => 2, "2" =>, "3" =>

id: 2
description: "pick 1, 2, 3/ some storry line"
inputs: "1" =>, "2" =>, "3" => 3

id: 3
description: " storyline...123...."
inputs: "1" =>, "2" =>, "3" =>
Run Code Online (Sandbox Code Playgroud)

通常,数据将来自文件。

这是一个示例(尚未编译或调试):

struct Scene
{
    Scene(int id_, int description_)
        : id(id_)
        , description(description_)
    {
    }

    int id;
    std::string description;
    std::map<std::string, int> inputToNextScene;
 };

void main(int, char **) 
{
    std::map<int, Scene> scenes;

    int ids = [1,2,3];
    std::string descriptions = ["first", "second", "third"];
    int nextScenes [3][3] = [ [1, 2, 3], [1, 3, 2], [1, 2, 0]];
    std::string input[3] = ["1", "2", "3"];

        for (int i = 0; i != 3; ++i)
        {
            scenes[ ids[i] ] = Scene(ids[i], descriptions);

            Scene& scene = scenes.at(ids[i]);

            for (int j = 0; j != 3; ++j)
            {
                scene.inputToNextScene[ input[j] ] = nextScenes[i][j];
            }
    }

    int currentScene = 1;

    std::string input;

    while (currentScene != 0)
    {
         Scene& scene = scenes.at(currentScene);

         std::cout << scene.description;
         //Maybe put in a prompt and check currentscene against previous before      printing description
         std::cin >> input;
         if (scene.inputToNextScene.find(input) != scene.inputToNextScene.end())
         {
             currentScene = scene.inputToNextScene.at(input);
         }
    }

    cout << "The end!";
}
Run Code Online (Sandbox Code Playgroud)