我正在实现一个统计+成就系统。基本结构是:
- 一项成就有许多相关的统计信息,这种关系必须将每项成就与所需的统计信息(及其价值)相关联。例如,Achievement1需要值为50(或更大)的Statistic1和值为100(或更高)的Statistics2
- 给定一个统计数据,我还需要知道相关的成就是什么(以便在统计数据发生变化时进行检查)
Stats和Achievements都有一个唯一的id。
我的问题是我不知道什么是最好的数据结构来表示它。顺便说一下,我正在使用:
SparseArray<HashMap<Statistic, Integer>> statisticsForAnAchievement;
对于数组的索引为Achievement ID并且HashMap包含Statistic/TargetValue对的第一点。和a:
SparseArray<Collection<Achievement>> achievementsRelatedToAStatistic;
对于第二个点,索引是StatisticID,项目是与成就相关的集合。
然后我需要处理这两个对象,保持它的连贯性。
有没有一种更简单的表达方式?感谢
作为Statistic
(或一组Statistics
)描述Achievement
,该Statistic
/s不应该存储在Achievement
类中吗?例如,改进的Achievement
类:
public class Achievement {
SparseArray<Statistic> mStatistics = new SparseArray<Statistic>();
// to get a reference to the statisctics that make this achievement
public SparseArray<Statistic> getStatics() {
return mStatistics;
}
// add a new Statistic to these Achievement
public void addStatistic(int statisticId, Statistic newStat) {
// if we don't already have this particular statistic, add it
// or maybe update the underlining Statistic?!?
if (mStatistics.get(statisticId) == null) {
mStatistic.add(newStat);
}
}
// remove the Statistic
public void removeStatistic(int statisticId) {
mStatistic.delete(statisticId);
}
// check to see if this achievment has a statistic with this id
public boolean hasStatistics(int statisticId) {
return mStatistic.get(statisticId) == null ? false : true;
}
// rest of your code
}
此外,Statistic
类应该将其目标值(Statistic1的50值)作为字段存储在其中。
一项成就有许多相关的统计数据,这种关系必须将每个成就与所需的统计数据关联起来值)。例如,Achievement1需要具有值的Statistic150(或更大)和值为100(或更高)的Statistic2。
统计信息已经存储在成就中,所以你所要做的就是存储成就的id(或成就本身)的数组/列表,这样你就可以访问取得这些成就的统计信息。
如果有统计数据,我还需要知道相关的成就是什么(以便在统计信息发生变化时进行检查。
您可以使用上面的成就数组/列表,对它们进行迭代,并检查该成就是否包含特定的Statistic
:
ArrayList<Achievement> relatedAchievements = new ArrayList<Achievement>();
for (Achievement a : theListOfAchievments) {
if (a.hasStatistics(targetStatistic)) {
relatedAchievements.add(a); // at the end this will store the achievements related(that contain) the targetStatistic
}
}
另一种选择是在某个地方有一个静态映射,存储哪些成就具有Statistic
,该映射将在每次调用addStatictic
或removeStatistic
方法时更新。
关于您的代码,如果您不需要Statistic
对象,并且只想保留对其id
的引用,那么您可以使用改进statisticsForAnAchievement
SparseArray<SparseIntArray> statisticsForAnAchievement;
// the index of the SparseArray is the Achievement's id
// the index of the SparseIntArray is the Statistic's id
// the value of the SparseIntArray is the Statistic's value