Search code examples
godotgdscript

How can I assign a value to x according to y


I have this code that is very annoying to write but does the job, I was wondering if there was a function or class of some sort to help me.

Here's my function:

func add_health():
    if wave in range(10,20):
        enemy_health = 2
    elif wave in range(20,30):
        enemy_health = 3.5
    elif wave in range(30,40):
        enemy_health = 5
    elif wave in range(40,50):
        enemy_health = 6.5
    elif wave in range(50,59):
        enemy_health = 8
    elif wave in range(60,69):
        enemy_health = 9.5
    else:
        enemy_health = 1

Solution

  • If your wave variable is an integer, this is simple1. If it is not, you should be able to cast it to an int for the same effect. Making it an input to the function makes this simple (since you can force the conversion).

    It looks like you increase the enemy_health value 1.5 per 10 wave (at least until 70, where you revert to 1). So simply divide wave by 10 and then multiple by 1.5, and add it to an offset. You may need some special handling for base cases (wave <10 or >=70).

    Without considering those edge cases, your function becomes

    func add_health(current_wave: int):
        # Parentheses probably unnecessary, but useful for clarity
        enemy_health = ((current_wave/10) * 1.5) + 0.5
    

    1 Dividing two integers results in an integer, discarding any remainder. So 53/10 == 5