Делаем консольную игру. Я хочу, чтобы игра закончилась, когда они получают 0 HP

0

В настоящее время я создаю игру, в которой он включает HP (здоровье персонажа) и хочет знать, как сделать игру законченной, когда она достигнет 0 HP для игрока. Может кто-нибудь мне помочь? Кроме того, мой текущий код до сих пор приклеен ниже, если необходимо.

//Important:
//finalHp = hp - 10;
//cout << "Name: " << name << "   |   " << "Age: " << age << "   |   " << "Sex: " << sex << "   |   " << "Race: " << race << "   |   " << "HP: " << finalHp << endl;

#include <iostream>
#include <string>
using namespace std;

int main()
{
    //sets strings and starting hp
    string name;
    string age;
    string sex;
    string race;
    string input;
    int hp = 20;

    //creating your character
    cout << "Welcome to xVert77x first ever published game!\nWhen answering questions you must either capitalize the first letter not\ncapitalize anything at all and must spell things correctly.\n(This rule excludes your name. You can make your name\nXxXxsNipERkIll360n0Sc0peSkIllZxXxX.)\n\nHave Fun!\n" << endl;
    cout << "Enter a character name: ";
    cin >> name;
    cout << "You have a very strange name... Enter a character age: ";
    cin >> age;
    cout << "Enter a character sex (M/F)(That means no aliens. Sorry ET): ";
    cin >> sex;
    cout << "Enter a character race (Human/Dwarf/Beast)(Still no aliens): ";
    cin >> race;
    cout << "Character created! Bringing you to your HUD..." << endl;

    //hud
    cout << "Name: " << name << "   |   " << "Age: " << age << "   |   " << "Sex: " << sex << "   |   " << "Race: " << race << "   |   " << "HP: " << hp << endl;

    //first question to player
    cout << "\nYou see a man. Do you kill him?\n1. Yes\n2. No" << endl;
    cin >> input;
    if (input == "yes" || input == "Yes")
    //if they choose yes it will take 5HP
    {
        cout << "You killed him! You lost 5 HP in the battle.\nThere was no reward because you shouldn't\nkill helpless people. :(" << endl;
        hp -= 5;
        cout << "Name: " << name << "   |   " << "Age: " << age << "   |   " << "Sex: " << sex << "   |   " << "Race: " << race << "   |   " << "HP: " <<hp << endl;
    }
    //if they choose no it will do nothing
    else if (input == "no" || input == "No")
    {
        cout << "You decided otherwise. That was a very smart decision." << endl;
        cout << "Name: " << name << "   |   " << "Age: " << age << "   |   " << "Sex: " << sex << "   |   " << "Race: " << race << "   |   " << "HP: " << hp << endl;
    }

    //next question to the player
    cout << "\nYou come to a fork in the road. Do you go right or do you go left? " << endl;
    cin >> input;
    if (input == "right" || input == "Right")
    //when they choose right this will happen
    {
        cout << "\nYou find a health potion and gain 7 HP!" << endl;
        hp += 7;
        cout << "Name: " << name << "   |   " << "Age: " << age << "   |   " << "Sex: " << sex << "   |   " << "Race: " << race << "   |   " << "HP: " << hp << endl;
    }
    //if you choose the left path
    else if (input == "left" || input == "Left")
    {
        cout << "\nYou fall into quicksand and barely make it out alive and then go to the path to the right. -10 HP." << endl;
        hp -= 10;
        cout << "Name: " << name << "   |   " << "Age: " << age << "   |   " << "Sex: " << sex << "   |   " << "Race: " << race << "   |   " << "HP: " << hp << endl;
    }


    cout << "\n\nEnd of game. For now... Press <enter> to exit...";
    cin.get();
    cin.get();

    return 0;
}
  • 0
    Итак, как вы планируете изменить HP? 20-10 никогда не будет ноль.
  • 3
    Для этого вам определенно необходим цикл, например, while (hp> 0) {…} или do {…} while (hp> 0);
Показать ещё 1 комментарий
Теги:

1 ответ

0
Лучший ответ

Ваш int main() настроен таким образом, который выходит в самом конце, с return 0; выражение. Как и остальные ветки if (...), вы проверяете текущую сумму hp после вычитания некоторого значения. Когда это достигает (или падает ниже) нуля, вы можете просто вывести сообщение, а затем (из вашей main функции) выйти (возврат 0 внутри main файла эффективно останавливает вашу программу).

В общем, "еще ли умер игрок?" проверка будет чем-то, что вы будете делать более одного раза, а сама проверка (вместе с любым сообщением "вы умерли") будет одинаковой, независимо от того, где по разным ветвям if() это фактически произошло.

Я бы создал новый метод, например bool isPlayerDead(int currentHP) {... } который вы могли бы вызвать после каждого из проверок вашего состояния:

int main()
{
    // ...your setup stuff here...
    int hp = 20;

    // ...the first of your if() checks here...

    if (isPlayerDead(hp))
    {
        showPlayerDeathMessage();
        return 0;
    }

    // ...if you got here, the player is not yet dead... do some more if() checks...

    if (isPlayerDead(hp))
    {
        showPlayerDeathMessage();
        return 0;
    }

    // ...and again, player is not dead, so so some more...
    // (and repeat this process for a while...)


    // Finally, if you get here, the player did NOT die while playing. Maybe
    // print a "Wow! You're still alive!" message before exiting.
    return 0;
}

Конечно, вы организуете это позже, чтобы делать циклы, иметь больше контента и т.д., Но похоже, что это должно по крайней мере дать вам указание в правильном направлении.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню