dynamo
dynamo

Reputation: 309

Is BFS or DFS an efficient search algorithm for Ms Pacman

I am working on implementing a search algorithm for the Ms Pacman AI. I thought it would be a good idea to start off with some basic searches like BFS or DFS. I just implemented a BFS but when i ran my code, ms pacman ran into a wall. I was wondering, is there something i could improve with my BFS code or is it just not sufficient enough?

    public MOVE BFS(Game game){
        EnumMap<Constants.GHOST,MOVE> ghostMove = new EnumMap<>(Constants.GHOST.class);
        MOVE bestMove = MOVE.NEUTRAL;
        Queue<Game> q = new LinkedList<>();
        q.add(game.copy());
        while(!q.isEmpty()){
            Game current = q.peek();
            q.remove();
            for (MOVE move : current.getPossibleMoves (current.getPacmanCurrentNodeIndex())) {
                Game neighbor = game.copy();
                neighbor.advanceGame(move, ghostMove);
                q.add(neighbor);
                if ((current.getNumberOfActivePills() == 0) && (current.getNumberOfActivePowerPills() == 0)) {
                    return move;
                }
            }
        }
        return bestMove;
    }

Upvotes: 1

Views: 449

Answers (1)

nickrl21
nickrl21

Reputation: 106

I'm going to assume your intention with using BFS to solve Ms Pacman in the most efficient way IE the shortest path. I think there are some issues with your BFS but its hard to know exactly what every function call is doing without access to the rest of your code. Something that might be a bug in your code is you are never setting bestMove to anything other than MOVE.NEUTRAL, that could explain running into a wall. Typically with BFS you are looking to find the shortest path to a specific target and you will want to avoid back tracking by keeping track of visited spaces. It might help to get really comfortable with a BFS for solving a maze or something simpler before applying it to your game.

If I were to implement something like that using bfs I would use bfs to find the path to the nearest pill and return that path. I would then use that path to move Ms Pacman to the pill one step at a time. Then once she eats the pill I would repeat this process until there are none left. I'm not sure that bfs is the best algorithm for Pacman but it should work, just might not result in the AI being the best player though. Also to prevent the the player from getting stuck I would only keep track of visited spaces for a single path to a pill then reset it with each new path.

Sounds like a fun project, Good Luck!

Upvotes: 1

Related Questions