我正在编写一个足球模拟器来娱乐,但我不确定如何组织我的球员的属性评级。我知道随着我改进游戏,属性的数量会发生变化。我需要单独访问每个,即
SoccerPlayer.getSpeed()
SoccerPlayer.getShooting()
我还知道我希望能够使用单个函数对它们进行平均以获得总体评分。
SoccerPlayer.getOverall()
我的第一个倾向是使用列表或数组,并用常量来定义数组中每个属性的索引。
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);
}
这样,每当我添加一个新属性时,我只需要更改总常量,并添加一个新的索引常量,总函数将始终起作用。但是有更好的方法吗?
最佳答案
您可以使用枚举作为属性,使用 map 作为评级:
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;
}
然后要添加新属性,只需将其添加到枚举中即可。
当您调试时,评级会更容易理解,因为属性有名称而不是数字。
此外,如果您想在属性中添加比例因子之类的内容(例如,速度的权重是射击的两倍),那么枚举是一个方便的放置位置。
关于java - 组织数据的最佳方式: variable number of specific datapoints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12118773/