2015-02-04 2 views
2

Извините за то, что вы новичок. Как мне вернуться к строке кода сразу после вызова attackRat()? После того, как крыса мертва, я хочу, чтобы программа пришла сюда, как мне это сделать? Спасибо и извините, если я буду глуп.Как вернуться к строке после вызова функции?

void ratCave() { 

    location = "rat cave"; 
    system("cls"); 
    cout << "\n You arrive at the cave where two rats greet you at the entrance." << endl; 
    cout << "\n What would you like to do?" << endl; 
    cout << "\n 1. Attack the rats" << endl; 
    cout << "\n 2. Open backpack" << endl; 
    cout << "\n> "; 
    cin >> input; 
    switch (input) { 

     case 1: 
     attackRat();  
     // I want the program to come here once the rat is dead. 

     case 2: 
     backpack(); 

    } 
} 

void attackRat() { 

    srand (time(NULL)); 

    damage = rand() % 10 + 10; 
    ratDamage = rand() % 5 + 5; 

    if (start == 1) { 

     ratHealth = rand() % 20 + 30; 
     turn = rand() % 2; 

     if (turn == 1) { 
      system("cls"); 
      cout << "\n The rat have the first turn." << endl; 
      cout << "\n "; 
      system("pause"); 

      health = health - ratDamage; 
      system("cls"); 
      cout << "\n The rat attacks you for " << ratDamage << " health!" << endl; 
      cout << "\n "; 
      system("pause");  
     } 

     else { 
      system("cls"); 
      cout << "\n You have the first turn." << endl; 
      cout << "\n "; 
      system("pause");  
     } 
    } 

    start = 0; 

    system("cls"); 
    cout << "\n Your health: " << health << endl; 
    cout << "\n Rat health: " << ratHealth << endl; 
    cout << "\n What do you do?" << endl; 
    cout << "\n [1] Attack rat" << endl; 
    cout << "\n [2] Use a potion" << endl; 
    cout << "\n> "; 
    cin >> input; 
    switch (input) { 

     case 1: 
     ratHealth = ratHealth - damage; 
     system("cls"); 
     cout << "\n You attack the rat for " << damage << " damage!" << endl; 
     cout << "\n "; 
     system("pause"); 

     if (ratHealth < 1) { 
      ratHealth = 0; 
      system("cls"); 
      cout << "\n You killed the rat!" << endl; 
      cout << "\n "; 
      system("pause"); 
      // Does something go here to return it to the bit I want? 
     } 

     health = health - ratDamage; 
     system("cls"); 
     cout << "\n The rat attacks you for " << ratDamage << " damage!" << endl; 
     cout << "\n "; 
     system("pause"); 

     if (health == 0) { 
      system("cls"); 
      cout << "\n You died!" << endl; 
      cout << "\n "; 
      system("pause"); 
      exit(0);  
     } 

     case 2: 
     attackRat(); 

    } 
} 
+4

Вы должны захватить [хорошую книгу] (http://stackoverflow.com/q/388242/1782465) и посмотреть понятие, как петля и оператор 'return'. – Angew

+2

Если вы не собираетесь открывать рюкзак автоматически после атаки крысы, вам, вероятно, понадобится инструкция 'break' после' attackRat() '. Как правило, в конце каждого случая внутри коммутатора хорошая практика иметь инструкцию 'break', если у вас нет веских оснований для этого. – Logicrat

+3

Помимо вопроса, вы почти наверняка хотите «break;» в конце каждого раздела «case». Без этого, если пользователь решит атаковать крысу, они также * откроют обратную сторону. – Josh

ответ

4

Только вернулся из attackRat():

// Does something go here to return it to the bit I want? 
return; 

Затем, когда вы вернулись в ratCave():

// I want the program to come here once the rat is dead. 
cout << "\nYup, the rat's dead and we're back in the rat cave."; 
+0

@ 6502 Фактически, он будет (частично случайно) работать во всех случаях - нет никакого кода между рекурсивным вызовом 'attackRat()' и концом функции. – Angew

+3

Я отказываюсь опубликовать ответ с участием longjmp. – Quentin

+0

@angew: doh ... вы правы – 6502

4

Вместо вызова attackRat() изнутри самого attackRat сделать петлю использовать нормальный петля с:

for(;;) { 
    ... code to repeat forever ... 
} 

, то вы можете использовать return, чтобы вернуться к тому, кто называется функция

Смежные вопросы