Distribute value across array w/ nested loop

  • My player has 9 weapons and each one has its own energy which is stored in an array. There are pickups to restore energy. If the currently selected weapon is full, but others are low, I want to distribute the restored energy to them evenly.

    My idea was to loop through the energy array as many times as the energy refill. If an energy is lower than max, 1 is added to it and 1 is added to a local var counter. If that counter is equal to the energy refill, the loop is stopped. This way, if there's only 1 weapon with low energy, then it'll get 1 energy with each loop until it's over. If multiple weapons are low on energy, they'll each get 1 until the refill amount is met, at which point the loop is stopped.

    I dunno if it's my code or the method as a whole but it doesn't quite work - too much energy is being restored. Any other ideas or examples floating around?

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • This should do it I think.

    "energy" is the amount of energy to add

    "slot" is the selected weapon

    "num_full" is the number of weapons with full energy, so the loop knows when to stop. To make it work when you don't have some weapons just keep the weapons you don't have with full energy.

    variable slot=0
    variable energy=10
    variable num_full=0
    
    Array.At(slot) + energy <= 100
    ---> set array at slot to Array.At(slot) + energy
    ---> set energy to 0
    else
    ---> array: set at slot to 100
    ---> set energy to Array.At(slot) + energy -100
    ---> set num_full to 1
    
    while
    num_full<9
    energy>0
    ------> set num_full to 0
    --- array: for each x
    ------ array.curValue < 100
    ------ energy > 0
    ---------> set array at array.curX to Array.At(array.curX) + 1
    ---------> subtract 1 from energy
    ------ array.curValue = 100
    ---------> add 1 to num_full[/code:2dhud75g]
Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)