非常简单的C 文本冒险的代码结构
Code Structure for Very Simple c++ Text Adventure
我正在尝试在C 中编写一个简单的文本冒险游戏,但是随着现在的时间越来越长,我正在寻找有关如何更好地构建代码的建议。
游戏非常简单,这实际上是我与C 一起玩的机会,因为我对它是相对较新的。我将一块文本打印到终端,向玩家提出问题,然后用一个新问题重复该过程。代码的每个"节点"看起来像这样:
string agreechoice1;
void Choice1()
{
cout << "some text describing situation, then the question.
Usually a choice between A or B nn";
while (!(agreechoice1 == "A" || agreechoice1 == "B"))
{
cin >> agreechoice1;
if (agreechoice1 == "A")
{
Choice2();
return;
}
if (agreechoice1 == "B")
{
Choice3();
return;
}
cout << "if they havent chosen A or B this will tell
them that, and they will have another chance to try. nn";
}
return;
}
因此,选择一个将它们将它们发送到Choice2((,这将与此处相同的事情。
我的问题是我应该如何构建这个?什么是好的C 练习?我现在处于有14个"选择"的情况下,因此我有14次对此代码的块。最好将它们中的每一个都放在单独的文件中,然后通过创建一个主文件将它们全部链接在一起?还是还有另一种我没有想到的更好的结构方法?
作为次要问题,这个代码块是"有效"的块 - 即,有没有更好的方法来执行我在这里尝试做的事情?
谢谢!(PS,这是我第一次在此处发布问题,所以如果我违反了任何规则或其他任何规则!(
有几种方法可以解决此问题,每次您必须考虑对体系结构的简单性。
这个问题可以描述为带有节点的图。请参阅节点图架构。每种情况(问题(都可能是一个节点,并且它们可以连接到其他几个节点。我建议使用C 库,而不是实现您自己的图形功能。像Boost的图库
最简单的解决方案之一就是您开始的。每种情况下的单独功能。一遍又一遍地导致新功能。但是,实现,更难修改并具有大量重复代码非常简单。例如,答案部分。
如注释中所述,您可以在时内使用开关语句来简化体系结构。易于添加新答案具有很大的优势。
cin >> agreechoice1
switch (agreechoice1)
case "A" :
Choice2();
break;
case "B" :
Choice3();
break;
// New answer as seen above
case "Z" :
Choice42();
break;
如果您移至OOP,则可以使用类。我将创建一个名为Choice的类,并用构造函数描述情况,可能的答案以及下一个选择。像
#include <iostream>
#include <string>
#include <map>
class Question {
std::string questionText;
std::map<std::string, Question*> answersAndNextQuestions;
public:
Question(const std::string& textToAsk) {
questionText = textToAsk;
}
void AddAnswer(std::string answerText, Question* nextQuestion) {
answersAndNextQuestions[answerText] = nextQuestion;
}
void Ask() {
std::cout << questionText << std::endl;
std::string answer;
std::cin >> answer;
// should handle invalid answers
answersAndNextQuestions[answer]->Ask();
}
};
int main()
{
Question first("Is this the first?");
Question second("Is this the second?");
Question third("Is this the third?");
first.AddAnswer("Yes", &second);
first.AddAnswer("No", &third);
first.Ask();
}
相关文章:
- 孤立代码块在结构中引发异常
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 为什么Microsoft在新代码中使用结构而不是类?
- 如何使用结构体在C++中更改这些代码?
- 在 Golang 中等C++结构中提供代码提示/标记
- clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) - 体系结构的未定义符号 x86_64:
- 如何知道用于实现标准代码段的确切数据结构和算法,例如在C++STL中?
- 我觉得我放入结构中的输入代码可以压缩,关于如何在保持代码简短的同时保持数据个性化的任何建议?
- 如何大致将 cpp 代码结构转换为 python
- 设计许多单例代码结构的更好方法
- 在正确性或良好的代码结构方面,这种动态对象创建看起来如何
- 不同版本的设备的代码结构
- 非常简单的C 文本冒险的代码结构
- Windows MSG 结构与旧项目代码结构 MSG 冲突
- 我可以让 c++ 代码结构相互看到吗?
- 存储类指针矢量(RPG代码结构)
- Rcpp:将数据帧与 Rcpp(内联)一起使用时推荐的代码结构
- 破译c++代码:结构中的函数与结构同名
- c++代码结构转换成HTML文件
- 有没有可以可视化c++代码结构的程序?