So basically I have a GridWorld project that I am doing right now in the AP Comp Sci class. I am doing Pacman. Here is my code for the action method (for those unfamiliar with GridWorld, the act method is called every time the actor has to make a new move):
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"; } } }
The reason for the strange formulation in the last two statements is bc. I want Pacman to be able to teleport to a real game. Now when I start the game, it works in about 90% of cases, but in the other 10% I get IllegalArgumentException bc, it says I'm trying to go to a place that is not on the board (for example, (9, -1) and (9.21)). I want to know how I can catch or throw or what I need to do to prevent this from happening. I never used a catch or toss, so also try to explain your gratitude for the reasoning!
source share