Minimax, Expectimax,


In this project, you will design agents for the classic version of Pac-Man. Along the way, you will implement both minimax and expectimax search and try your hand at evaluation function design.

The code for this project contains the following files, available as a zip archive.

Key files to read: This is the file where you will program. It is where all of the pac-man algorithms will reside. The main file that runs Pac-Man games. This file also describes a Pac-Man GameState type, which you will use extensively in this project The logic behind how the Pac-Man world works. This file describes several supporting types like AgentState, Agent, Direction, and Grid. Useful data structures for implementing search algorithms.

Files you can ignore: Graphics for Pac-Man Support for Pac-Man graphics ASCII graphics for Pac-Man Agents to control ghosts Keyboard interfaces to control Pac-Man Code for reading layout files and storing their contents

What to submit: You will fill in portions of during the assignment. You should submit this file with your code and comments. Please do not change the other files in this distribution or submit any files other than You are welcomed to write supporting functions as you need them and place them in Do not change the existing function names because this will only mess up the autograder. Directions for submitting are on the Programming Project 0 website (same submission process as before).

How to submit: The assignment is to be submitted as follows. Log onto a corn machine, put your source code into a directory on the Stanford AFS space. Go into the directory that contains your source code. Then type: /usr/class/cs221/submitter/submit

You can submit multiple times and we will grade your latest submission -- so feel free to submit a lot. In fact why don't you try submitting right now (yes now). If you have problems submitting, please contact the TAs immediately. You will not get extensions because you waited until after the deadline to contact the TAs. See submitting for more details.

Evaluation: Your code will be autograded for technical correctness. Please do not change the names of any provided functions or classes within the code, or you will wreak havoc on the autograder. However, the correctness of your implementation -- not the autograder's judgements -- will be the final judge of your score. If necessary, we will review and grade assignments individually to ensure that you receive due credit for your work.

Academic Dishonesty: We will be checking your code against other submissions in the class for logical redundancy (as usual). If you copy someone else's code and submit it with minor changes, we will know. These cheat detectors are quite hard to fool, so please don't try. We trust you all to submit your own work only; please don't let us down. If you do, we will pursue the strongest consequences available to us, as outlined by the honor code.

Getting Help: You are not alone! If you find yourself stuck on something, contact the course staff for help. Office hours and piazza are there for your support; please use them. We want these projects to be rewarding and instructional, not frustrating and demoralizing. But, we don't know when or how to help unless you ask.


Reflex Agent
Minimax Agent
AlphaBeta Agent
Expectimax Agent
Eval Function
Due Date: Pac-man is due July 8th at 11:59pm (PDT).
Submit: You can submit multiple times. We will grade your latest submission.

Multi-Agent Pac-Man

First, play a game of classic Pac-Man:


Now, run the provided ReflexAgent in

python -p ReflexAgent

Note that it plays quite poorly even on simple layouts:

python -p ReflexAgent -l testClassic

Inspect its code (in and make sure you understand what it's doing.

1. Reflex Agent (3 points) 

A reflex agent chooses an action at each choice point by examining its alternatives via an action evaluation function.

Improve the action evaluation function evaluationFunction of ReflexAgent in to play respectably. The provided reflex agent code has some helpful examples of methods that query the GameState for information. A capable reflex agent will have to consider both food locations and ghost locations to perform well. Your agent should easily and reliably clear the testClassic layout:

python -p ReflexAgent -l testClassic

Try out your reflex agent on the default mediumClassic layout with one ghost or two (and animation off to speed up the display):

python --frameTime 0 -p ReflexAgent -k 1
python --frameTime 0 -p ReflexAgent -k 2

How does your agent fare? It will likely often die with 2 ghosts on the default board, unless your evaluation function is quite good.

Options: Default ghosts are random; you can also play for fun with slightly smarter directional ghosts using -g DirectionalGhost. If the randomness is preventing you from telling whether your agent is improving, you can use -f to run with a fixed random seed (same random choices every game). You can also play multiple games in a row with -n. Turn off graphics with -q to run lots of games quickly.

The autograder will check that your agent can rapidly clear the openClassic layout ten times without dying more than twice or thrashing around infinitely (i.e. repeatedly moving back and forth between two positions, making no progress).

python -p ReflexAgent -l openClassic -n 10 -q

Don't spend too much time on this question, though, as the meat of the project lies ahead.

Action Evaluation: The evaluation function you're writing is evaluating state-action pairs; in later parts of the project, you'll be evaluating states.

Inverse: As features, try the reciprocal of important values (such as distance to food) rather than just the values themselves.

Ghosts: you can never have more ghosts than the layout permits.

2. Minimax Agent (5 points)

Now you will write an adversarial search agent in the provided MinimaxAgent class stub in Your minimax agent should work with any number of ghosts, so you'll have to write an algorithm that is slightly more general than what appears in the textbook. In particular, your minimax tree will have multiple min layers (one for each ghost) for every max layer.

Your code should also expand the game tree to an arbitrary depth. Score the leaves of your minimax tree with the supplied self.evaluationFunction, which defaults to scoreEvaluationFunction. MinimaxAgent extends MultiAgentAgent, which gives access to self.depth and self.evaluationFunction. Make sure your minimax code makes reference to these two variables where appropriate as these variables are populated in response to command line options.

Important: A single search ply is considered to be one Pac-Man move and all the ghosts' responses, so depth 2 search will involve Pac-Man and each ghost moving two times.

Hints and Observations

  • The minimax values of the initial state in the minimaxClassic layout are 9, 8, 7, -492 for depths 1, 2, 3 and 4 respectively. Note that your minimax agent will often win (665/1000 games for us) despite the dire prediction of depth 4 minimax.
    python -p MinimaxAgent -l minimaxClassic -a depth=4
  • Pac-Man is always agent 0, and the agents move in order of increasing agent index.
  • All states in minimax should be GameStates, either passed in to getAction or generated via GameState.generateSuccessor. In this project, you will not be abstracting to simplified states.
  • On larger boards such as openClassic and mediumClassic (the default), you'll find Pac-Man to be good at not dying, but quite bad at winning. He'll often thrash around without making progress. He might even thrash around right next to a dot without eating it because he doesn't know where he'd go after eating that dot. Don't worry if you see this behavior, question 5 will clean up all of these issues.
  • When Pac-Man believes that his death is unavoidable, he will try to end the game as soon as possible because of the constant penalty for living. Sometimes, this is the wrong thing to do with random ghosts, but minimax agents always assume the worst:
    python -p MinimaxAgent -l trappedClassic -a depth=3
    Make sure you understand why Pac-Man rushes the closest ghost in this case.

3. Alpha-Beta Agent (5 points)

Make a new agent that uses alpha-beta pruning to more efficiently explore the minimax tree, in AlphaBetaAgent. Again, your algorithm will be slightly more general than the pseudo-code in the textbook, so part of the challenge is to extend the alpha-beta pruning logic appropriately to multiple minimizer agents.

You should see a speed-up (perhaps depth 3 alpha-beta will run as fast as depth 2 minimax). Ideally, depth 3 on smallClassic should run in just a few seconds per move or faster.

python -p AlphaBetaAgent -a depth=3 -l smallClassic

The AlphaBetaAgent minimax values should be identical to the MinimaxAgent minimax values, although the actions it selects can vary because of different tie-breaking behavior. Again, the minimax values of the initial state in the minimaxClassic layout are 9, 8, 7 and -492 for depths 1, 2, 3 and 4 respectively.

State Evaluation: The evaluation function in this part is the already written Agent evaluationFunction. You shouldn't change this function, but recognize that now we're evaluating *states* rather than actions, as we were for the reflex agent.
Speed: To increase the search depth achievable by your agent, remove the Directions.STOP action from Pac-Man's list of possible actions. Depth 2 should be pretty quick, but depth 3 or 4 will be slow. Don't worry, the next question will speed up the search somewhat.

4. Expectimax Agent (3 points)

Random ghosts are of course not optimal minimax agents, and so modeling them with minimax search may not be appropriate. Fill in ExpectimaxAgent, where your agent agent will no longer take the min over all ghost actions, but the expectation according to your agent's model of how the ghosts act. To simplify your code, assume you will only be running against RandomGhost ghosts, which choose amongst their getLegalActions uniformly at random.

You should now observe a more cavalier approach in close quarters with ghosts. In particular, if Pac-Man perceives that he could be trapped but might escape to grab a few more pieces of food, he'll at least try. Investigate the results of these two scenarios:

python -p AlphaBetaAgent -l trappedClassic -a depth=3 -q -n 10
python -p ExpectimaxAgent -l trappedClassic -a depth=3 -q -n 10

You should find that your ExpectimaxAgent wins about half the time, while your AlphaBetaAgent always loses. Make sure you understand why the behavior here differs from the minimax case.

5. Evaluation Function (3 points)

Write a better evaluation function for pacman in the provided function betterEvaluationFunction. The evaluation function should evaluate states, rather than actions like your reflex agent evaluation function did. You may use any tools at your disposal for evaluation, including your search code from the last project. With depth 2 search, your evaluation function should clear the smallClassic layout with two random ghosts more than half the time and still run at a reasonable rate (to get full credit, Pac-Man should be averaging around 1000 points when he's winning).

python -l smallClassic -p ExpectimaxAgent -a evalFn=better -q -n 10

Document your evaluation function! We're very curious about what great ideas you have, so don't be shy. We reserve the right to reward bonus points for clever solutions and show demonstrations in class.

Hints and Observations

  • As for your reflex agent evaluation function, you may want to use the reciprocal of important values (such as distance to food) rather than the values themselves.
  • One way you might want to write your evaluation function is to use a linear combination of features. That is, compute values for features about the state that you think are important, and then combine those features by multiplying them by different values and adding the results together. You might decide what to multiply each feature by based on how important you think it is.

6. Extensions (Optional)

Get creative! Pacman's been doing well so far, but what if things got a bit more challenging? If you are interested, try programming a more advanced Pac-man Agent and see how well it doesn against smarter foes in a trickier maze. In particular, the ghosts will actively chase Pacman instead of wandering around randomly, and the maze features more twists and dead-ends, but also extra pellets to give Pacman a fighting chance.

You're free to have Pacman use any search procedure, search depth, and evaluation function you like. If you are looking for inspiration, an interesting algorithm try Monte Carlo Tree Search. Monte Carlo Tree Search (or MCTS for short) is one of the most popular algorithms for cutting edge General Game Players.

python -l contestClassic -p ContestAgent -g DirectionalGhost -q -n 10

Project 1 is done. Go Pac-Man!