The idea here is to pick a skill at random for the player each round. Four skills will be chosen, they are all random, and the same skill can repeat multiple times.
The player has a skill level for each ability. The higher the skill level, the greater the chance that the skill will be chosen.
Rather than use floats and percentages, I have created this solution based on ranges and integers. The readability of the code is what I am concerned with here. Does it make sense from looking at it? Would more comments help, or should I use a different approach?
I am using this in a libGDX game, so I am limited to Java 6.
private Ability getRandomAbility() {
final Map<BZRange, Ability> abilityRanges = new HashMap<BZRange, Ability>();
int count = 0;
for (Ability ability : this.skillLevels.keySet()) {
int abilityLevel = this.skillLevels.get(ability);
BZRange abilityRange = new BZRange(count, count + abilityLevel);
abilityRanges.put(abilityRange, ability);
count += abilityLevel;
//increase the count by an extra one so that the ranges dont overlap
count++;
}
int randomNumber = this.random.nextInt(count);
for (BZRange range : abilityRanges.keySet()) {
if (range.contains(randomNumber)) {
return abilityRanges.get(range);
}
}
return null;
}
Here is the BZRange
class, it is very simple:
public class BZRange {
private int low;
private int high;
public BZRange(int low, int high){
this.low = low;
this.high = high;
}
public boolean contains(int number){
return (number >= this.low && number <= this.high);
}
}