我创建吃豆子游戏。我有大小为 15x15 的数组,总共 225 个字段。当我从 255 移动到 ie256 时,我得到了 ArrayIndexOutOfBoundsException,这是有道理的。所以我可以抓住它并做一些操作,假设我设置了 pacman 的新起点。但是,如果我从 75 场转到 74 场,则什么也没有发生。所以我问,我能不能以某种方式抓住这个并做一些操作,就像我上面提到的那样。
你不应该依赖ArrayIndexOutOfBoundsException正常的逻辑。此异常表明存在编程错误。
相反,您应该在增加索引之前检查它:
if (currentIndex == 255) {
// "special logic"
} else {
// "usual logic"
}
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您还可以处理任何“特殊”索引,例如
if ((currentIndex + 1) % 15 == 0) {
// "special logic"
} else {
// "usual logic"
}
Run Code Online (Sandbox Code Playgroud)
另一点:如果您正在编写二维游戏,请考虑使用两个索引 - x 和 y。每次移动都会修改 x 和/或 y,它们可以像 pacman 一样轻松“环绕”(例如 13 -> 14 -> 15 -> 1 -> 2 -> ...)。并且仅在需要访问字段元素时才将 (x,y)-Pair 转换为索引:
// Assuming that x and y are 1-based, not 0-based:
public FieldElement getFieldElementAtPosition(final int x, final int y) {
final int index = (y - 1) * FIELD_WIDTH + x - 1;
return fieldArray[index];
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
46 次 |
| 最近记录: |