非常简单的C 文本冒险的代码结构

Code Structure for Very Simple c++ Text Adventure

本文关键字:代码 结构 冒险 简单 非常 文本      更新时间:2023-10-16

我正在尝试在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();
}