package tsp.pacman; import java.util.HashMap; import java.util.List; public class GhostDirectional implements Ghost{ private HashMap prevDirections; private char getRandomDirection(PacmanState state, Position position){ List moves = state.findPossibleMoves(position); char resDirection = 'S'; if (moves.isEmpty()) return 'S'; char direction = 'S'; if (prevDirections.containsKey(position)) direction = prevDirections.get(position); int index = (int)(Math.random() * moves.size()); Position target = moves.get(index); if (target.getRow() == position.getRow() + 1) resDirection = 'D'; else if (target.getRow() == position.getRow() - 1) resDirection = 'U'; else if (target.getCol() == position.getCol() + 1) resDirection = 'R'; else if (target.getCol() == position.getCol() - 1) resDirection = 'L'; // To avoid up turns if (moves.size() > 1){ if ((direction == 'D' && resDirection == 'U') || (direction == 'U' && resDirection == 'D') || (direction == 'R' && resDirection == 'L') || (direction == 'L' && resDirection == 'R') ){ return getRandomDirection(state, position); } } return resDirection; } public GhostDirectional(){ prevDirections = new HashMap<>(); } private Position getNextPosition(PacmanState state, Position position){ Position resPos = position; char direction = prevDirections.get(position); if (direction == 'U'){ Position posUp = new Position(position.getRow() - 1, position.getCol()); if (state.isLegalMove(posUp)){ resPos = posUp; } else { prevDirections.put(position, getRandomDirection(state, position)); return getNextPosition(state, position); } } else if (direction == 'D') { Position posDown = new Position(position.getRow() + 1, position.getCol()); if (state.isLegalMove(posDown)){ resPos = posDown; } else { prevDirections.put(position, getRandomDirection(state, position)); return getNextPosition(state, position); } } else if (direction == 'R') { Position posRight = new Position(position.getRow(), position.getCol() + 1); if (state.isLegalMove(posRight)){ resPos = posRight; } else { prevDirections.put(position, getRandomDirection(state, position)); return getNextPosition(state, position); } } else if (direction == 'L') { Position posLeft = new Position(position.getRow(), position.getCol() - 1); if (state.isLegalMove(posLeft)){ resPos = posLeft; } else { prevDirections.put(position, getRandomDirection(state, position)); return getNextPosition(state, position); } } return resPos; } @Override public Position chooseAction(PacmanState state, Position position) { if (!prevDirections.containsKey(position)){ prevDirections.put(position, getRandomDirection(state, position)); } char direction = prevDirections.get(position); if (direction == 'S' || state.findPossibleMoves(position).size() > 2) prevDirections.put(position, getRandomDirection(state, position)); Position resPos = getNextPosition(state, position); prevDirections.put(resPos, prevDirections.get(position)); return resPos; } }