mardi 18 avril 2017

Using Random Number inside of Switch Statement Cases

I am a novice C++ programmer making a project for a computer science class. I am having a problem with a certain section of code that is supposed to give an enemy a random set of items based on their preset difficulty level. I am using a modified template version of Bjorne's random function. When I used his original version I still had the problem:

// random number generator from Stroustrup: 
// http://ift.tt/1nQyPrV
template<class T>
T rand_num(const T & low, const T & high)
{
    static std::default_random_engine re{};
    using Dist = std::uniform_int_distribution<T>;
    static Dist uid{};
    return uid(re, Dist::param_type{ low,high });
}

When I test the section by making an EnemyAI object that encapsulates the OffensiveEntity and setting the difficulty to, say, 1, it always sets the random number to 1 and always choses, in this case, the Health potion. If I were to set the second if statement to a condition of if (tempRandom == 1) it would choose the stick.

void EnemyAI::Equip()
{
    m_offensiveEntity->ClearItems();

    std::vector<std::shared_ptr<Item>> tempItems;

    int tempRandom = 0;

    switch (m_difficultyLevel)
    {
    case 0:
    case 1:
    {
        tempRandom = rand_num<int>(1, 4);
        if ((tempRandom == 1) || (tempRandom == 2) || (tempRandom == 3) || (tempRandom == 4))
            tempItems.push_back(CreateTempItem("Health Potion : HP", 3, 3, 
-10, Result::Effect::nothing));
        if (tempRandom == 3)
            tempItems.push_back(CreateTempItem("Wooden Stick : DMG", 5, 2, 10, Result::Effect::nothing, 3, 13, Result::Effect::nothing));
        break;
    }
    case 2: ... etc

What's the cause of this problem? Here's the output:

Health Potion : HP name
3 durability
-10 total damage
3 energy cost
0 effect

When typing in this:

int main()
{
     std::shared_ptr<EnemyAI> offensiveEntityInterface =
         std::make_shared<EnemyAI>(EnemyAI("Dank Memerson", 50, 1));

     offensiveEntityInterface->Equip();
    for (auto & i : offensiveEntityInterface->GetEquiped())
    {
        std::cout << i->GetName() << " name \n";
        std::cout << i->GetHP() << " durability \n";
        std::shared_ptr<const Result> tempResult = i->Use();
        std::cout << tempResult->m_totalDamage << " total damage \n";
        std::cout << tempResult->m_energyCost << " energy cost \n";
        std::cout << tempResult->m_effect << " effect \n";
    }
    std::cin.get();
    return 0;
}

Heres the source code in a pastebin http://ift.tt/2o0Nwx4




Aucun commentaire:

Enregistrer un commentaire