Array problem

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By chaosreborn1

I have this array represent a character stat:

var player_strength_array = [2, 3, 3, 4, 5, 5, 7]

and these variables:

var player_strength
var player_starting_strength = 0

then I match player_strength to player_strength to player_strenght_array

func _process(delta): 
         player_strength = player_strength_array[player_starting_strength]

I add a function to modify the stat:

func increase_stat():
        player_starting_strength += 1

The reason I do it like this is because I don’t want to just simply add 1 point to the stat. Instead I want to make it like a milestone thing like when gain 1 Strength point, it pushes the tracker in the array foward by 1.

Is there a better way to do this?

:bust_in_silhouette: Reply From: DaddyMonster

As things stand your _process method is setting player_strength 100s of times a second with the same thing over and over. Which reminds me way too much of my ex so let’s change that. :wink:

Let’s see what increase_stat can do on its own. The ideal in computing is to have one method handle one task.

I’ve changed the naming a bit, yours weren’t terrible, just Player.player_strength is better as Player.strength. And there’s a loose convention to denote arrays with an s.

var strengths = [2, 3, 3, 4, 5, 5, 7]
var lvl = 0
var strength = strengths[lvl]

func level_up():
    lvl = min(strengths.size()-1, lvl+1)
    set_strength()

func set_strength():
    strength = strengths[lvl]

Now, you can just call Player.level_up() when you want to… Well, level up. Note how easy it would be to make levelling up do more in the future, so it makes the code more future proof, scalable and all the good stuff.

ps. The min thing is just to prevent it crashing if you call it too many times, so you don’t look up an index which isn’t there (eg strengths[8] is a crash).