Sebpt55
Sebpt55

Reputation: 13

Is there a way to minimise the amount of IF statements?

My code is full of If statements and I want to reduce the amount if not get rid of them all. How do I do that? Any other tips and improvements is much appreciated thanks! I've just begun learning to code and have followed a tutrioal to write this but am struggling to understand how to minimise the amount of IFs.

void Combat() {
    //combat simiulator
    CombatHUD();
    int userAttack;
    int userDamage = 1000; //8 * level / 2;
    int monsterAttack = 6 * monsterlevel / 2;

    if (character.totalHealth >= 1 && monsterHealth >= 1) {
        std::cout << "\n";
        std::cout << "1. Attack\n";
        std::cout << "2. Block\n";
        std::cout << "3. Run\n";
        std::cout << "\n";
        std::cin >> userAttack;

        if (userAttack == 1) {
            //User Attack
            std::cout << "Attacking... you did " << userDamage << " to the " << currentMonster << std::endl;
            monsterHealth = monsterHealth - userDamage;
            Sleep(1000);
            CombatHUD();
            if (monsterHealth >= 1) {
                std::cout << "Monster is attacking... \n";
                character.totalHealth = character.totalHealth - monsterAttack;
                std::cout << "You recieved " << monsterAttack << " damage " << std::endl;

                if (character.totalHealth <= 0) {
                    character.totalHealth = 0;
                    system("cls");
                    std::cout << "You died! Game over!";
                    Sleep(2000);
                    exit(0);
                }
            }
            else if (monsterHealth <= 0) {
                monsterHealth = 0;
                if (character.level != character.maxlevel) {
                    character.current_xp += monsterXp;
                    LevelUp();
                }
                std::cout << "\n";
                std::cout << "You defeated " << currentMonster << " you get " << monsterXp << "XP.\n";
                Sleep(2000);
                HUD();
            }
            Sleep(1000);
            Combat();
        }
        else if (userAttack == 2) {
            //User Block. broken?
            std::cout << "Blocking\n";
            int i = rand() % 100 + 1;
            if (i >= 50) {
                std::cout << "You blocked the incoming attack\n";
                character.heal = character.level * 10 / 2;
                std::cout << "you have been healed for " << character.heal << std::endl;
                character.totalHealth += character.heal;
                Sleep(1000);
                Combat();
            }
        }

        else if (userAttack == 3) {
            //User escape
            std::cout << "You try to run\n";
            int x = rand() % 100 + 1;
            if (x >= 50) {
                std::cout << "You run away\n";
                HUD();
            }
            else {
                std::cout << "You failed to run away \n";
                std::cout << "Monster does a critical hit! \n";
                character.totalHealth -= monsterAttack + 10;
                std::cout << "You suffered " << monsterAttack + 10 << "Your current health is " << character.totalHealth << std::endl;
                Sleep(2000);
                Combat();

            }

        }
        else {
            std::cout << "Invalid Input\n";
            Sleep(500);
            Movement();
        }
    }
}

void Movement() {
    //user movement. enhance?
    int choice;
    std::cout << "\n\n";
    std::cout << "1. Move forward\n";
    std::cout << "2. Chill\n";
    std::cout << "3. Move Backwards\n";
    std::cout << "\n";

    std::cin >> choice;

    if (choice == 1) {
        int temp = rand() % 100 + 1;
        std::cout << "You begin moving forward...\n";
        if (temp >= 50) {
            Monster();
            std::string tempName = monsterName[rand() % currentMonsterNames];
            std::cout << "A " << tempName << "! Get ready to fight it!\n";
            currentMonster = tempName;
            Sleep(1000);
            Combat();
        }
        std::cout << "You find nothing\n";
        Sleep(1000);
        HUD();

    }
    else if (choice == 2) {
        std::cout << "You want to chill for the rest of the day\n";
        if (character.totalHealth <= 99) {
            character.totalHealth += 10 * character.level;
        }
        std::cout << "You healed by chilling Health is now " << character.totalHealth << std::endl;
        Sleep(1000);
        HUD();
    }
    else if (choice == 3) {

        std::cout << "You begin moving backwards...\n";
        std::cout << "You're going no where\n";
        Sleep(2000);
        system("cls");

    }
    else {
        std::cout << "Invalid Input\n";
        Sleep(500);
        Movement();
    }






}

void Monster() {
    //monster creator
    monsterHealth = 30; {
    monsterlevel = (rand() % 3) + character.level;
}

    monsterHealth = (rand() % 30) * monsterlevel;

    monsterXp = monsterHealth;

    if (monsterHealth == 0)
        Monster();
    if (monsterlevel == 0)
        Monster();


}

void LevelUp() {
    //level up mechanic
    if (character.current_xp >= character.xp_to_level) {
        character.xp_to_level += floor(character.level + 15 * pow(2, character.level / 7));
        character.totalHealth = floor(character.totalHealth + 10 * pow(2, character.level / 8));

        if (character.level >= character.minLevel && character.level <= character.maxlevel) {
            character.level++;
        }
        else {
            character.level = 5;
        }

        character.maxHealth = character.totalHealth;
        std::cout << "Ba Da Bing! You've leveled up! You're max health has increased!" << std::endl;
        Sleep(2000);
        LevelUp();
    }

    Sleep(2000);
    HUD();

}

Upvotes: 0

Views: 165

Answers (2)

Bitwize
Bitwize

Reputation: 11210

This is an extremely broad, open-ended question for software design in general -- not just C++.

For the most part, you won't be able to remove ifs since you have conditional logic -- and this is fine. However there are design practices you can follow so that there are less if statements per function:

  • Factoring logic into smaller functions that isolate their concerns. For example, each of the different Combat actions could be individual functions. This doesn't reduce ifs, but limits the amount of nesting per-function to where it's logically needed.

  • Finding repeated code or patterns, and extracting them into functions. Again, this helps limit the ifs to where they are needed

  • Using a switch case in place of if/else ladder

  • With smaller functions, you can change if statements to check for early termination cases and return early to avoid nesting. This keeps nesting shorter, since the main branch after an early return is implicitly the else. For example:

void check_user_death()
{
  // Instead of 'if (character.totalHealth <= 0)'
  if (character.totalHealth > 0) {
    return;
  }
  system("cls");
  std::cout << "You died! Game over!";
  Sleep(2000);
  exit(0);
}

All of the above suggestions are just overall software design topics, and are not strictly-speaking specific to C++


As an unrelated note, you might want to look into using loops (e.g. for or while), since your Combat function seems to recursively call itself in a few cases -- which could potentially result in stack overflows.

Upvotes: 0

Iaotle
Iaotle

Reputation: 86

Here's your Movement function represented as a switch:

void Movement() {
    //user movement. enhance?
    int choice;
    std::cout << "\n\n";
    std::cout << "1. Move forward\n";
    std::cout << "2. Chill\n";
    std::cout << "3. Move Backwards\n";
    std::cout << "\n";

    std::cin >> choice;

    switch (choice)
    {
        case 1:
            int temp = rand() % 100 + 1;
            std::cout << "You begin moving forward...\n";
            if (temp >= 50) {
                Monster();
                std::string tempName = monsterName[rand() % currentMonsterNames];
                std::cout << "A " << tempName << "! Get ready to fight it!\n";
                currentMonster = tempName;
                Sleep(1000);
                Combat();
            }
            std::cout << "You find nothing\n";
            Sleep(1000);
            HUD();
            break;
        case 2:
            std::cout << "You want to chill for the rest of the day\n";
            if (character.totalHealth <= 99) {
                character.totalHealth += 10 * character.level;
            }
            std::cout << "You healed by chilling Health is now " << character.totalHealth << std::endl;
            Sleep(1000);
            HUD();
            break;
        case 3:
            std::cout << "You begin moving backwards...\n";
            std::cout << "You're going no where\n";
            Sleep(2000);
            system("cls");
            break;
        default:
            std::cout << "Invalid Input\n";
            Sleep(500);
            Movement();
    }
}

Learning switch statements and having even better function separation will usually reduce the amount of ifs. Ifs themselves are most likely unavoidable though.

Upvotes: 1

Related Questions