gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 01:58:16 28 4
gpt4 key购买 nike

我正在使用 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
}
}
}
}

如果不分支 if 语句,我将如何实现这个概念?

最佳答案

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

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

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

你有一个代表结束的场景。

你有一个循环:

loop until current scene is the end
Print current scene description
Ask for input
Evaluate input

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

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

因此,对于您的示例(显然不完整,但应该让您了解所需的数据),您将拥有以下场景:

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" =>

通常数据来自文件。

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

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!";
}

关于c++ - 基于文本的游戏非分支 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17645838/

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