简体   繁体   中英

Creating a variable based on increments of another variable

I'm very new to Java and have been self-teaching myself. I'm creating an RPG game where skills reflect a "modifier", you gain or lose modifiers based on your overall skill in that field.

For example, if your "strength" skill is at 10, you gain a +0 modifier towards anything that requires strength. If it's 12, you gain a +1 modifier, 14 is +2 and so forth.

Is there some way I can do without having to create a huge table listing all the increments as if statements?

It sounds like you just want some formula to calculate the modifiers. Guessing from your question, the formula would be something along the lines of:

int modifier = Math.floor((skillLevel - 10) / 2);

If you want different formulas for different types of skills, then you're probably going to want a Skill class with different constants stored in it, used to calculate the formula. For instance, if strength is calculated as above, but intelligence needs to be at 15 before you start gaining a modifier, you could do this:

public class Skill {
    int baseLevel;

    public Skill(int level) {
        this.baseLevel = level;
    }

    public int getModifier(int skillLevel) {
        return Math.floor((skillLevel - baseLevel) / 2);
    }
}

Create the strength instance of Skill with a baseLevel of 10 and the intelligence instance of Skill with a baseLevel of 15. If your formula for calculating the modifier is more complicated, you can change this class accordingly.

For the example you gave you could do this:

modifier = (skill - 10) / 2;

Which says every two points > 10 gives +1 modifier. This is a simplistic solution as it doesnt account for skills < 10 but you get the idea.

Look at Java Collections Framework and choose a class to store your tables indicating what modifier applies to given scores. You want to be able to load the data initially, then lookup the answer for a score as needed. Therefore you may want to look at some class implementing java.util.map . I'll leave that learning exercise to you ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM