2017-06-25 60 views
-1

請看看這段代碼,我會解釋:想回去功能上if/else語句

void GameOver() 
{ 
    cout << "\nWelp, you died. Want to try again?" << endl; 
    cin >> choice; 
    if (choice == "Yes" || "yes") 
    { 
     /*This is where I want the code. I want it to go back to the last 
     function that the player was on.*/ 
    } 

    if (choice == "No" || "no") 
    { 
     cout << "Are you sure? The game will start over when you open it back up." << endl; 
     cin >> choice; 
     if (choice == "No" || "no") 
     { 
      cout << "Well, bye now!" << endl; 
      usleep(1000000); 
      exit (EXIT_FAILURE); 
     } 
    } 
    return; 
} 

我想這樣,當我在GAMEOVER功能選擇「是」,我想要一個if/else聲明說:「如果你來自這個功能,那麼你會去那功能」,你明白我在說什麼?

例如,假設我在GameOver函數中,而我來自FightProcess函數。我選擇「是」,那麼它會去Town功能。 我將如何編碼?

+0

從'void'你是指一個返回void的函數嗎? –

回答

1

首先,像這樣的語句:

if (choice == "Yes" || "yes") 

編碼錯誤,並且將始終評估爲真。您需要改用此:

if (choice == "Yes" || choice == "yes") 

或者更好,使用不區分大小寫的比較函數,就像這樣:

if (strcmpi(choice.c_str(), "Yes") == 0) 

其次,除非你添加一個輸入參數,或者使用全局變量, GameOver()不知道是誰叫它。所以你想要做的事不屬於GameOver()本身。它屬於調用函數。 GameOver()如果用戶選擇不繼續,則退出遊戲。這是它應該做的。如果遊戲沒有退出,調用函數應該決定如何重試。例如:

void GameOver() 
{ 
    cout << "\nWelp, you died. Want to try again?" << endl; 
    cin >> choice; 
    //if (choice == "Yes" || choice == "yes") 
    if (strcmpi(choice.c_str(), "Yes") == 0) 
     return; 

    cout << "Are you sure? The game will start over when you open it back up." << endl; 
    cin >> choice; 
    //if (choice == "No" || choice == "no") 
    if (strcmpi(choice.c_str(), "No") == 0) 
     return; 

    cout << "Well, bye now!" << endl; 
    usleep(1000000); 
    exit (EXIT_FAILURE); 
} 

void FightProcess() 
{ 
    ... 
    if (defeated) 
    { 
     GameOver(); 
     Town(); 
     return; 
    } 
    ... 
} 

或者,如果Town()是叫FightProcess()功能:

void FightProcess() 
{ 
    ... 
    if (defeated) 
    { 
     GameOver(); 
     return; 
    } 
    ... 
} 

void Town() 
{ 
    ... 
    FightProcess(); 
    ... 
} 

或者,它可能會更有意義有FightProcess()循環,而不是:

void FightProcess() 
{ 
    ... 
    do 
    { 
     ... 
     if (won) 
      break; 
     GameOver(); 
     ... 
    } 
    while (true); 
    ... 
} 

查看如何當你不把限制性邏輯放在不屬於它的地方時,事情會變得更加靈活?

+0

謝謝,它工作! – Ejay

1

我會推薦使用GameOver函數中的參數。然後,每次你想要去其他地方時,你都可以傳遞一個不同的參數。例如,從函數1調用GameOver(1),從函數2調用GameOver(2)

這假設從GameOver返回並在調用函數中執行不同的選項不是一個選項。

0

或者您可以選擇在FightProcess()中觸發一個事件。

如: -

void FightProcess(){ 
    ... 
    if(...){ 
     observer.send("FightProcess"); // or with more information. 
           //observer.send("FightProcess",Avatar::Killed); 
     GameOver(); 
    } 

} 

而在GAMEOVER(),您可以查詢觀察者查找最後一個事件了。