3 回答
TA贡献1817条经验 获得超14个赞
这是一个非常好的问题。因为每个 if-else 都是一样的;您检查某个滚动是否在某个范围内,然后返回一个字符串,您可以只使用枚举。相对于您正在处理和用此数据表示的内容,可以改进枚举名称以及元素名称。
public String generatePassageSection() {
int roll = roll();
Message message = Stream.of(Message.values()).filter(m -> m.inBounds(roll)).findAny().orElse(null);
return message == null ? null : message.message;
}
enum Message {
FIRST(1, 2, "passage goes straight for 10 feed."),
SECOND(3, 5, "passage ends in the door to a chamber."),
THIRD(6, 7, "door to right (main passage continues straight for 10 ft)"),
FOURTH(9, 10, "door to left (main passage continues straight for 10 ft)"),
FIFTH(10, 11, "passage turns to left and continues for 10 ft"),
SIXTH(12, 13, "passage turns to right and continues for 10 ft"),
SEVENTH(14, 16, "passage ends in door to chamber"),
EIGHTH(17, 17, "Stairs, (passage continues straight for 10 ft)"),
NINTH(18, 19, "Dead end"),
TENTH(20, 20, "Wandering Monster (passage continues straight for 10 ft)");
;
private final int minimumRollInclusive;
private final int maximumRollInclusive;
private final String message;
Message(int minimumRollInclusive, int maximumRollInclusive, String message) {
this.minimumRollInclusive = minimumRollInclusive;
this.maximumRollInclusive = maximumRollInclusive;
this.message = message;
}
boolean inBounds(int roll) {
return roll >= minimumRollInclusive && roll <= maximumRollInclusive;
}
}
int roll() {
return 0; // use ur code
}
另外,应该注意的是,Enum#values 每次调用时都会创建一个新的数组对象,因此值得对其进行缓存。
TA贡献1921条经验 获得超9个赞
如果您只是想减少 if 语句的数量,您可以添加一组可能的结果,在适当的骰子上对每个结果进行索引,然后返回该索引处的值。我不会把它全部写给你,但它看起来有点像这样:
public String generatePassageSection(String[] diceRolls){ return diceRolls[roll()]; }
TA贡献1828条经验 获得超3个赞
更喜欢数据结构而不是代码。
final private static String text[] = {
"passage goes straight for 10 feet.", // 1, 2
"passage ends in door to a chamber.", // 3, 4, 5
"door to right (main passage continues straight for 10 ft)", // 6, 7
"door to left (main passage continues straight for 10 ft)", // 8, 9
"passage turns to left and continues for 10 ft", // 10, 11
"passage turns to right and continues for 10 ft", // 12, 13
"passage ends in door to chamber", // 14, 15, 16
"Stairs, (passage continues straight for 10 ft)", // 17
"Dead end", // 18, 19
"Wandering Monster (passage continues straight for 10 ft)" // 20
}
final private static int index[] = {
0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 6, 7, 8, 8, 9
}
public String generatePassageSection() {
return text[index[roll()-1]];
}
手动构造的索引数组对文本数组的顺序和内容有隐式假设。就本次例行的情况和规模而言,我认为这是合理的;我不建议将其作为一般做法。
这隐含地假设 roll() 已知能够可靠地返回 1 到 20(含)范围内的结果;如果你不能信任它,应该添加错误检查。
添加回答
举报