How can I increment a variable without exceeding a maximum value?

前端 未结 14 1573
别跟我提以往
别跟我提以往 2021-01-30 12:03

I am working on a simple video game program for school and I have created a method where the player gets 15 health points if that method is called. I have to keep the health at

14条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-30 12:57

    I am just going to offer a more reusable slice of code, its not the smallest but you can use it with any amount so its still worthy to be said

    health += amountToHeal;
    if (health >= 100) 
    { 
        health = 100;
    }
    

    You could also change the 100 to a maxHealth variable if you want to add stats to the game your making, so the whole method could be something like this

    private int maxHealth = 100;
    public void heal(int amountToHeal)
    {
        health += amountToHeal;
        if (health >= maxHealth) 
        { 
            health = maxHealth;
        }
    }
    

    EDIT

    For extra information

    You could do the same for when the player gets damaged, but you wouldn't need a minHealth because that would be 0 anyways. Doing it this way you would be able to damage and heal any amounts with the same code.

提交回复
热议问题