您可以通過使用數據驅動設計擺脫分支if語句。
在基地你有一個循環檢查輸入,並使用當前上下文評估輸入,然後更改上下文。
這些if語句中的每一個都變成了「場景」(或房間或狀態,選擇對您正在編寫的程序有意義的名稱)。每個場景都有一個ID,一個描述以及一組有效的輸入和場景編號。
你有一個場景代表結束。
你有一個循環,雲:
評估輸入覈對當前場景的有效輸入的輸入,如果有效集當前場景中指定的場景。
該程序將當前場景初始化爲第一個場景,然後啓動循環。
因此,對於你的例子(顯然是不全面的,但應該給你你需要的數據的想法),你將有一個場景:
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!";
}
那麼爲什麼你可能需要'(userChoice == 1)'兩次,第二次查看switch語句 – aaronman
將邏輯上分離的邏輯和動作組織成不同的功能。當然,你需要內部的條件,但一旦你嘗試過,你會立即看到這樣做的優勢。 –