I'm writing a soccer simulator for fun, and I'm unsure how to organize my player's attribute ratings. I know that the number of attributes will change as I improve the game. I'll need to access each individually, i.e.
SoccerPlayer.getSpeed()
SoccerPlayer.getShooting()
I also know that I'll want to be able to average them with a single function to get an overall rating.
SoccerPlayer.getOverall()
My first inclination is to use a list or array, with constants to define each attribute's index within the array.
static final int SPEED_INDEX = 0;
static final int SHOOTING_INDEX = 1;
static final int NUM_ATTRIBUTES = 2;
int[] attributes = new int[NUM_ATTRIBUTES];
int getSpeed() {
return attributes[SPEED];
}
int getOverall() {
int total = 0;
for (int i : attributes) {
total += i;
}
return (total / attributes.length);
}
That way, whenever I add a new attribute, I only have to change the total constant, and add a new index constant, and the total function will always work. But is there a better way to do this?
You could use an enum for your attributes and a map for the ratings:
enum Attributes {
SPEED, SHOOTING;
};
private Map<Attributes,Integer> ratings = new LinkedHashMap<Attributes, Integer>();
int getRating(Attribute attribute) {
return ratings.get(attribute);
}
int getSpeed() {
return getAttribute(Attributes.SPEED);
}
int getOverall() {
int total = 0;
for (int i : ratings.values()) {
total += i;
}
return total / Attributes.values().length;
}
Then to add a new attribute just add it to the enum.
When you're debugging, the ratings will be easier to understand because the attributes have names instead of numbers.
Also, if you want to add something like a scale factor to the attributes (e.g. speed is weighted twice as much as shooting) the enum is a convenient place to put it.