[英]Text-based Game non branching if statements
我正在用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!";
}
我為每個選項創建一個單獨的函數:
void doStoryLine1() {
cout << "Options: ..." << endl;
if(userChoice == 1)
fightDragon();
else if(userChoice == 2)
fightOrcs();
else if(userChoice == 3)
marryPrincess();
else
/* invalid option? */
}
void doStoryLine2() {
...
}
void selectStoryLine() {
cout << "Options: ..." << endl;
if(userChoice == 1)
doStoryLine1();
else if(userChoice == 2)
doStoryLine2();
else if(userChoice == 3)
doStoryLine3();
else
/* invalid option? */
}
您描述的問題似乎是異步編程中的常見問題(例如Node JS)。
您可以通過使用控制流編程(例如序列/瀑布和承諾)來打破這些循環。
注意:我之前沒有使用過這個標題,但它的工作方式與JS中的期貨類似: Futures vs. Promises
JS中的代碼(你在C ++中得到了想法)
/** Sequence **/
new Sequence()
.then(function(next, arg1, arg2) {
// stage 1...
next(arg1, arg2);
})
.then(function(next) {
// stage 2...
next();
});
/** Promise **/
var a = Promise();
function stage1() {
// capture input 1...
a.fulfill(input1);
}();
a.when(function(err, data) {
console.log(data);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.