2017-06-25 59 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(),您可以查询观察者查找最后一个事件了。