所以基本上我有一个 GridWorld 项目,我现在正在我的 AP Comp Sci 课程中做。我在做吃豆人。这是我的 act 方法代码(对于那些不熟悉 GridWorld 的人,每次预期演员做出新动作时都会调用 act 方法):
public void act()
{
Location loc = getLocation();
if(direction==null) {
}
else if(direction.equals("NORTH")) {
Location next = loc.getAdjacentLocation(loc.NORTH);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
if(getGrid().get(next) instanceof Food)
addFood();
moveTo(next);
direction = "NORTH";
}
}
else if(direction.equals("SOUTH")) {
Location next = loc.getAdjacentLocation(loc.SOUTH);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
if(getGrid().get(next) instanceof Food)
addFood();
moveTo(getLocation().getAdjacentLocation(getLocation().SOUTH));
direction = "SOUTH";
}
}
else if(direction.equals("EAST")) {
Location next = loc.getAdjacentLocation(loc.EAST);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
if(getGrid().get(next) instanceof Food)
addFood();
moveTo(getLocation().getAdjacentLocation(getLocation().EAST));
direction = "EAST";
}
else if(getLocation().getCol()==20 && getLocation().getRow()==9) {
moveTo(new Location(9,0));
direction = "EAST";
}
}
else if(direction.equals("WEST")) {
Location next = loc.getAdjacentLocation(loc.WEST);
if(getGrid().isValid(next) && (getGrid().get(next)==null || getGrid().get(next) instanceof Food)) {
moveTo(getLocation().getAdjacentLocation(getLocation().WEST));
direction = "WEST";
}
else if(getLocation().getCol()==0 && getLocation().getRow()==9) {
moveTo(new Location(9,20));
direction = "WEST";
}
}
}
最后两个 if 语句中的奇怪措辞的原因是因为我希望 Pacman 能够在真实游戏中传送。现在,当我运行游戏时,大约 90% 的时间它可以工作,但在另外 10% 的情况下,我得到一个 IllegalArgumentException bc,它说我正在尝试移动到一个不在棋盘上的地方(例如(9,-1 ) 和 (9,21))。我想知道如何接球或扔球,或者我需要做些什么来阻止这种情况的发生。我从来没有使用过 catch 或 throw 所以也请尝试解释你的推理谢谢!