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

前端 未结 14 1597
别跟我提以往
别跟我提以往 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 13:01

    I know this is a school project, but if you wanted to expand your game later on and be able to upgrade your healing power, write the function like so:

    public void getHealed(healthPWR) {
        health = Math.min(health + healthPWR, 100);
    }
    

    and call out the function:

    getHealed(15);
    getHealed(25);
    

    ...etc...

    Furthermore you can create your max HP by creating a variable that is not local to the function. Since I don't know what language you're using, I will not show an example because it might have the wrong syntax.

提交回复
热议问题