Eat every pellet to clear the maze, and avoid the ghosts, which catch Pac-Man on contact unless they are scared. Pellets, power pellets and eaten ghosts all score points.
In watch mode, press RUN AGENT, then PAUSE and STEP to inspect its moves. In You play mode, choose Continuous or Step by step. Use W A S D, arrow keys, or the buttons below. Space or STOP holds Pac-Man still while ghosts keep moving; PAUSE freezes the game. Turn on SOUND in the navigation to hear the arcade effects.
The line under the board names the algorithm on each side. The ghosts move after Pac-Man each turn.
| FEATURE | VALUE | WEIGHT | CONTRIBUTES |
|---|
Pac-Man moves first each turn, then every ghost moves. The ghosts are run by one of two policies: A* search plans their routes, or chance ghosts roll fixed odds. The learned agent scores each legal move as a weighted sum of 13 hand-designed features, and its weights were learned by Q-learning from 3000 games of self-play, in which the agent plays against the A* ghosts.
The maze is a grid of cells. Walls and open cells are fixed. Some open cells hold a pellet, and the larger glowing dots are power pellets. Pac-Man can move or wait while every ghost takes a step. While any ghost is blue, Pac-Man skips one movement in every four turns (75% speed). The game is won when no pellets remain, and lost when a ghost catches Pac-Man.
Eating a pellet scores 10 points, a power pellet 50, and clearing the maze adds 500. A power pellet makes every ghost scared for 8 turns. The rule is applied on each step onto a power cell, whether or not its pellet is still there; waiting on the cell does not renew it1. A scared ghost that Pac-Man reaches is eaten for 200 points and returns to its starting cell. Any other ghost that meets him ends the game2. A game ends at its turn limit: 300 on the small mazes, 630 on Arcade, and 825 on Google Doodle3.
Each turn is resolved in six steps. A ghost already on Pac-Man's new cell is resolved first, so a scared ghost on that cell is eaten. Then the win check runs, because a cleared maze ends the game before the ghosts move. The ghosts then move from one shared snapshot of the board, and a ghost that steps onto Pac-Man's cell is resolved a second time. Last, the scared timers count down and the turn counter advances4.
function TURN(state, action):
pac ← the cell Pac-Man reaches with action
award points for a pellet or power pellet on pac, and scare every ghost if pac stepped onto a power cell
if a ghost stands on pac:
if it is scared: eat it (200 points), send it home
otherwise: the game is lost
if no pellets remain: the game is won
every ghost moves one step, by GHOST-MOVE or by CHANCE-MOVE
if a ghost now stands on pac: resolve it as above
count down the scared timers and check the turn limit
return the new state
function TURN(state, action):
pac ← DESTINATION(state, action) # wait or slowed turns stay put
points ← 0
if pac is in pellets:
remove pac from pellets
if pac is a power cell: points ← points + 50
otherwise: points ← points + 10
if pac moved onto a power cell: # eaten or not
set every ghost's scared timer to 8
ghosts, gained, died ← MEET(ghosts, pac) # ghosts already on pac
points ← points + gained
if died:
return LOST
if pellets is empty:
return WON with points + 500
pac-dist ← DISTANCES(maze, pac) if any ghost is scared, otherwise nothing
for each ghost i: # all choose from the same snapshot
if the policy is chance:
next, heading ← CHANCE-MOVE(maze, ghost)
otherwise:
next, target, route ← GHOST-MOVE(maze, ghost, i, pac, action, pac-dist)
heading ← ghost.heading # A* ghosts never read it
move the ghost to next and set its heading
ghosts, gained, died ← MEET(ghosts, pac) # ghosts that stepped onto pac
points ← points + gained
if died:
return LOST
for each ghost: scared ← max(0, scared − 1)
if turn + 1 ≥ maze turn limit:
status ← TIMEOUT
return the new state with points and status
The full version has three ideas that are easy to miss. Stepping onto a power cell scares the ghosts again even when its pellet was eaten earlier, since the check is only on the cell. Waiting still permits ghost collisions. And the first collision check also covers a swap: a ghost on the cell Pac-Man moves into is still there when that move is resolved, so it is caught before any ghost moves. The second check catches only ghosts that step onto Pac-Man during the ghost move.
The ghosts plan with A* search, a shortest-path method that always expands the queued cell with the smallest estimated total cost. It keeps a queue ordered by f = g + h, where g is the number of steps so far and h is a heuristic, an estimate of the steps still needed. Here h is the Manhattan distance, the grid distance that ignores walls.
Here n is a cell, g(n) is the length of the best route found so far to n, and r_n and c_n are its row and column. Every move costs one step, and the Manhattan distance never overestimates on such a grid. So the first time the goal leaves the queue, its route is a shortest one.
Ties in f go to the cell with the smaller h, which is nearer the goal and cuts the number of cells explored6. A cell is closed once it has been expanded, and a stale queue entry for a closed cell is skipped. Each cell stores a parent, the cell it was reached from, and the route is read back from the goal.
function ASTAR(maze, start, goal):
queue ← [start], ordered by g + h, where h = MANHATTAN(cell, goal)
g[start] ← 0
while the queue is not empty:
cur ← the entry with the lowest f
if cur = goal:
return the route back from goal through parent
for each open neighbour nb of cur:
if g[cur] + 1 < g[nb]:
g[nb] ← g[cur] + 1
parent[nb] ← cur
push nb with f = g[nb] + MANHATTAN(nb, goal)
return None
function ASTAR(maze, start, goal):
if start = goal:
return [start]
best-g ← {start: 0}
parent ← {start: NO-CELL}
h0 ← MANHATTAN(start, goal)
heap ← [(h0, h0, start)] # entries are (f, h, cell)
closed ← empty set
while heap is not empty:
(f, h, cur) ← pop the smallest entry of heap
if cur = goal:
route ← [cur]
while parent[last cell of route] ≠ NO-CELL:
append parent[last cell of route] to route
reverse route
return route
if cur is in closed: # a stale entry, already expanded
(skip to the next pop)
else:
add cur to closed
g ← best-g[cur] + 1
for each neighbour nb of cur:
if nb is NO-CELL or nb is in closed:
(skip nb)
else if nb is not in best-g or g < best-g[nb]:
best-g[nb] ← g
parent[nb] ← cur
h ← MANHATTAN(nb, goal)
push (g + h, h, nb) onto heap
return None
The full version keeps the queue as a heap, a structure that returns the smallest entry in logarithmic time, and it keeps a separate record of the best g seen for each cell. Those two records are why a cell may appear in the queue more than once. Cells are expanded only once, so the search always finishes.
Breadth-first search (BFS) finds the walking distance from one cell to every other cell in one pass. Each cell is reached from its nearest neighbour already reached, and that neighbour's distance plus one is its own. The features and the scared ghosts' flight both use these distances7.
Each ghost has a personality. Ghost i, counting from zero in the order of the maze's G cells, takes the personality at position i \bmod 4 of the list chaser, ambusher, scatter, chaser8. Neon Lanes therefore has a chaser, an ambusher and a scatter ghost. Vault adds a second chaser as its fourth.
A ghost that is not scared plans an A* route to its target and takes the first step of it. If the route has no step, because the ghost already stands on its target, it steps to the neighbour nearest to Pac-Man by Manhattan distance11.
A scared ghost ignores its target. It steps to the neighbour with the largest walking distance from Pac-Man's new cell, and ties go to a random choice from the game's generator12.
function GHOST-MOVE(maze, ghost, pac, facing, pac-dist):
if ghost is scared:
step to the neighbour with the largest pac-dist, ties at random
return that cell, no target
target ← TARGET(maze, ghost, pac, facing)
route ← ASTAR(maze, ghost.pos, target)
if the route has a next cell:
step to route[1]
otherwise:
step to the neighbour nearest pac by Manhattan distance
return the cell, target, route
function GHOST-MOVE(maze, ghost, index, pac, facing, pac-dist):
options ← open neighbours of ghost.pos
if ghost.scared > 0:
best ← max of pac-dist[nb] over options
nxt ← random choice among options with pac-dist[nb] = best
return (nxt, no target, route (ghost.pos, nxt))
target ← TARGET(maze, ghost, index, pac, facing)
route ← ASTAR(maze, ghost.pos, target)
if route is not None and length of route > 1:
return (route[1], target, route)
nxt ← the option nb with the smallest (MANHATTAN(nb, pac), nb)
return (nxt, target, (ghost.pos, nxt))
function TARGET(maze, ghost, index, pac, facing):
if ghost is a chaser:
return pac
if ghost is an ambusher:
cell ← pac
if facing ≥ 0:
repeat 4 times:
nxt ← the neighbour of cell in direction facing
if nxt is NO-CELL: break
cell ← nxt
return cell
# scatter
if MANHATTAN(ghost.pos, pac) ≤ 4:
return corners[index mod 4]
return pac
In the full version, facing is the direction index of Pac-Man's move this turn, or −1 before he has moved. The index of a ghost is its position in the maze's list of ghosts, and it selects the corner for a scatter ghost. The ambusher's walk never leaves the maze, since it stops at a wall.
The chance policy does no planning. It does not look at Pac-Man, the pellets, or any route. Each ghost keeps a heading, the direction of its last move. Each turn it picks one open direction from fixed odds read relative to that heading: keep going 60%, turn left 15%, turn right 15%, reverse 10%13. The shares are renormalised over the open directions only, so a ghost in a corridor with one exit must take it.
Here d is a direction index in the order N, E, S, W (0 to 3), h is the ghost's heading, D is the set of open directions, and o(k) is the odds for turn k: 0.60 for straight, 0.15 for right (k = 1), 0.10 for back (k = 2), and 0.15 for left (k = 3). A ghost with no heading yet gives every open direction the same weight.
The draw uses one random number from the game's generator. It is scaled to the total weight, and the open directions are walked in order until it is used up. The ghost keeps its move's direction as its new heading14.
function CHANCE-MOVE(maze, ghost):
open ← the directions with an open neighbour
weight[d] ← the odds for d, read relative to ghost.heading
roll ← a random number in [0, 1) × the sum of the weights
for each d in open:
roll ← roll − weight[d]
if roll < 0:
return the neighbour in direction d, and d
return the last open direction
function CHANCE-MOVE(maze, ghost):
open_dirs ← [d for d in 0..3 if the neighbour in direction d is open]
if ghost.heading = NO-HEADING:
weights ← [1 for each d in open_dirs]
otherwise:
weights ← [CHANCE-ODDS[RELATIVE[(d − ghost.heading) mod 4]] for each d in open_dirs]
roll ← random number in [0, 1) × sum(weights)
for each (d, w) in (open_dirs, weights):
roll ← roll − w
if roll < 0:
return (neighbour in direction d, d)
return (neighbour in open_dirs[last], open_dirs[last]) # rounding only
# RELATIVE = (straight, right, back, left), the turn names by clockwise offset from the heading
# CHANCE-ODDS: straight 0.60, left 0.15, right 0.15, back 0.10
The shares were set by hand, not fitted to data. Chance ghosts do not change when Pac-Man is scared: they keep to the odds, and they are eaten only when Pac-Man lands on them. Only the A* ghosts flee1516. The match results later on the page compare both policies.
The reflex agent is a fixed rule with no search and no learning. It scores each legal move, and plays the highest score, breaking exact ties at random. Its value for a move a is
Here d is the walking distance from the destination to an active ghost, so the sum counts only the ghosts one or two steps away: 80 points for one step and 40 for two. The indicator \mathbf{1}_{\text{scared}} is 1 when the move eats a scared ghost. The term \text{food}(a) is the walking distance from the destination to the nearest pellet, and 0 when none remains. The values 1000, 40, 50 are hand-written, not tuned.
function REFLEX-SCORE(move):
if an active ghost is on the move's cell:
return −1000
score ← 0
for each active ghost one or two steps away:
score ← score − 40 × (3 − distance)
if the move eats a scared ghost:
score ← score + 50
return score − distance to the nearest pellet
function REFLEX-SCORE(s): # s: the position after the move
if any active ghost has distance 0 from the destination:
return −1000
score ← 0
score ← score − sum of 40 × (3 − d) for each active ghost with d in {1, 2}
if any scared ghost has distance 0 from the destination:
score ← score + 50
score ← score − (food, or 0 when no pellet remains)
return score
The random agent picks one legal move uniformly at random18. It is the floor that any learned policy should beat. In the benchmark below it cleared no maze in 400 games.
The Q-agent scores move a in position s with a Q-value, a weighted sum of a feature vector. A feature is a number computed from the position the move leads to, before the ghosts move. A weight sets how much its feature adds to the score. The score is linear in the features:
Here f(s, a) is the vector of 13 features of the position after move a, w is the vector of learned weights, and f_i and w_i are their i-th entries. The features express the trade-offs that matter: eat pellets and power pellets, avoid active ghosts, chase scared ghosts, avoid dead ends, and avoid traps that close a few turns later. The weights are learned, so the code does not fix how much any feature counts.
Distances are walking distances from the destination cell, so walls and corridors count as they do for a ghost21. A distance is divided by 10 and not passed through a reciprocal. A reciprocal would flatten out for far targets, so the model could not tell a pellet 15 steps away from one 25 steps away22.
Here d_{\text{pellet}} and d_{\text{power}} are the walking distances from the destination to the nearest pellet and the nearest power pellet, each taken as 0 when none remains. The sum \text{ghost\_near} runs over the active ghosts, those that can hurt Pac-Man, and each d_g is that ghost's walking distance from the destination. The range 6 is the distance at which an active ghost stops counting. The sum \text{scared\_near} runs over the scared ghosts at a distance of at least 1, with range 8. The count n_{\text{open}} is the number of open neighbours of the destination, so a low openness marks a dead end. The \text{trap} feature is large when a ghost is closing in on a place with few exits.
Five features are indicators, each 1 or 0: pellet (the move eats a pellet), power (it eats a power pellet), ghost_adjacent (an active ghost is one step from the destination), caught (an active ghost stands on it), and eat_ghost (it lands on a scared ghost). The bias is the constant 1. The last feature, survival, is described in the next section.
| Feature | What it measures | Learned weight |
|---|---|---|
| bias | Constant 1. Learns the typical value of a turn. | -236.366284 |
| pellet | 1 if the move eats a pellet. | 5.970195 |
| power | 1 if the move eats a power pellet. | 39.047522 |
| food | Walking distance to the nearest pellet, / 10 (0 when none remains). | -69.462897 |
| capsule | Walking distance to the nearest power pellet, / 10 (0 when none remains). | -21.996608 |
| ghost_near | Sum over active ghosts of max(0, 1 - d / 6), d = walking distance from the move. | -17.705702 |
| ghost_adjacent | 1 if an active ghost is one step from the move. | -3.078364 |
| caught | 1 if an active ghost stands on the destination (fatal). | 8.172549 |
| scared_near | Sum over scared ghosts of max(0, 1 - d / 8), for d at least 1. | 9.023088 |
| eat_ghost | 1 if the move lands on a scared ghost. | 76.037818 |
| openness | Open neighbours of the destination, / 4. Low values are dead ends. | 5.848713 |
| trap | ghost_near × (1 - openness): a ghost closing in on a dead end. | 10.632794 |
| survival | Turns Pac-Man survives after the move (up to 6), / 6. | 319.020104 |
How these were chosen: the features and their scales (ranges of 6 and 8 cells, distance divided by 10, openness by 4, survival by 6) were designed by hand. The weights were not set by hand: training started from zeros and learned all 13. The reward constants (1 per turn, 300 for being caught) are hand-set, and the point values come from the game rules. No tuning sweep over any of these is committed. Features overlap, so read the weights together: survival's 319.02 is about 53 per extra surviving turn (319.02 / 6).25
A static feature cannot see a trap two or three turns away, such as a corridor with a ghost waiting at its far end. The survival feature instead plays the game forward. For each legal move, the ghosts answer with their real logic, Pac-Man tries every legal move again, and so on, for up to H = 6 turns26. The depth is the number of turns Pac-Man survives. It is 0 if the move is fatal at once, and 6 if he survives the whole horizon.
Here s_a is the position after move a, H is the horizon of 6 turns, and A(x, p) is the number of the next p turns that a living position x survives under Pac-Man's best play. A game that is won counts as surviving, as does a position that survives the whole horizon. The feature is D / H, so it lies between 0 and 1 before its weight is applied.
The search is exact for the ghost AI, with one exception. A scared ghost's random tie-break uses a fixed seed of 0, so it can differ from the choice in a real game29. The results are memoised, meaning stored and reused, under the key (Pac-Man's cell, his last move, every ghost, the number of pellets left, the turns left). The key counts the pellets rather than naming them, so two positions that differ only in which pellets remain can share an entry30. The search always assumes the A* ghosts, even when the chance policy is chosen, so the feature is only an estimate under chance ghosts.
function SURVIVAL-DEPTHS(state):
for each legal move a:
if a is fatal at once: depth[a] ← 0
otherwise: depth[a] ← 1 + ALIVE(position after a, 5)
return depth
function ALIVE(state, plies):
if plies = 0 or state is over: return plies
best ← 0
for each legal move a:
if a is not fatal:
best ← max(best, 1 + ALIVE(position after a, plies − 1))
if best = plies: stop
return best
function SURVIVAL-DEPTHS(state, horizon = 6):
game ← a game on state.maze with seed 0
memo ← empty table
for each legal move a of state:
game.state ← state
turn ← game.step(a)
if death is in turn.events:
depth[a] ← 0
otherwise:
depth[a] ← 1 + ALIVE(game, game.state, horizon − 1, memo)
return depth
function ALIVE(game, state, plies, memo):
if plies = 0 or state is over:
return plies
key ← (state.pac, state.facing, state.ghosts, number of pellets in state, plies)
if key is in memo:
return memo[key]
best ← 0
for each legal move a of state:
game.state ← state
turn ← game.step(a)
if death is not in turn.events:
best ← max(best, 1 + ALIVE(game, game.state, plies − 1, memo))
if best = plies: stop # no better is possible
memo[key] ← best
return best
The memo table is a dictionary, so a position reached by two different orders of moves is solved once. The stop when best = plies is a pruning step: once the whole remaining horizon is survived, no other move can do better. Both functions only read the game through its turn step, so the search uses exactly the rules the game uses.
Q-learning learns the value of a move from experience: the reward the agent receives, and the value of the best move from the position it reaches next. Approximate means the values come from the feature weights, not from a table with one entry per position. After each turn, the agent compares the value it expected with a target built from what happened, and moves each weight in proportion to its feature:
Here r is the reward of the turn, s' is the position after the ghosts have moved, and the maximum runs over the legal moves a' in s'. The discount factor \gamma = 0.9 sets how much the next turn's value counts. The temporal-difference (TD) error \delta is the gap between the target and the expectation. The step size \alpha (the learning rate) is 0.01 at the start of training and falls to 0.001 by its end.
The maximum is over the next position's moves, so the update learns the value of the best play from there. This is Watkins' Q-learning, which is off-policy: the moves the agent actually makes, including random exploration, do not enter the target33. A weight moves only on turns where its feature is non-zero. The bias, which is always 1, moves on every turn, while the power feature moves only on turns that eat a power pellet.
The reward for a turn is the points it scores, minus 1 as a small cost per turn so that a quicker clear is preferred, minus 300 when Pac-Man is caught. The penalty is larger than the points available before a death. A game that times out is treated as ended, so its target is just the reward34.
The trainer's loop is shown below. It picks each move with \varepsilon-greedy exploration: with probability \varepsilon a uniformly random legal move, otherwise the move with the highest Q-value, with exact ties broken at random35. After each turn it calls the update once.
function TRAIN(episodes):
w ← zeros, one per feature
for each episode:
play one game with ε-greedy moves
after each turn, nudge w toward the target (TD-UPDATE)
return w
function TRAIN(episodes, seed, mazes, α, γ, ε):
rng ← random generator with seed
w ← [0, ..., 0] # 13 weights
recent ← []
for ep from 0 to episodes − 1:
progress ← min(1, ep / max(1, 0.8 × episodes))
eps ← ε-start + (ε-end − ε-start) × progress
step ← α-start + (α-end − α-start) × ep / max(1, episodes − 1)
game ← a new game on mazes[ep mod len(mazes)], seed ← rng.randrange(2^31)
feats ← FEATURES(game.state) # f(s, a) for each legal a
while game is not over:
values ← {a: w · feats[a] for each legal a}
if rng.random() < eps:
action ← a uniform random legal move
otherwise:
action ← the argmax of values, ties at random
turn ← game.step(action)
reward ← turn.points − 1, minus 300 if death is in turn.events
if game is over:
next-feats ← []
otherwise:
next-feats ← FEATURES(game.state)
TD-UPDATE(w, feats[action], reward, next-feats, step, γ)
feats ← next-feats
recent.append((final score, won))
if ep + 1 is a multiple of 25, or ep + 1 = episodes:
log the mean score and win rate of recent, then clear recent
return w
function TD-UPDATE(w, feats, reward, next-feats, α, γ):
target ← reward
if next-feats is not empty:
target ← target + γ × max over f in next-feats of (w · f)
error ← target − w · feats
for each i: w[i] ← w[i] + α × error × feats[i]
return error
The full version has three details that matter. The bootstrapped maximum is computed before any weight changes, so it uses the weights from before this turn. A game that ends, by a win, a death or a timeout, passes an empty list of next features, so its target is the reward alone. And the exploration coin and the move choice both draw from the trainer's own generator, so a run with the same arguments produces the same weights.
The trainer draws each game's seed from its own generator and never uses the benchmark seeds, so the results below are not training results37.
The shipped weights come from 3000 self-play games. The games alternate between Neon Lanes and Vault, starting from zero weights, with trainer seed 1. The defaults are set in the train command and in the train function, and the trained block of the weights file records the same settings383925.
Here ep counts episodes from 0, and N = 3000 is the number of episodes. The step size \alpha falls linearly from 0.01 to 0.001 across the whole run. The exploration rate \varepsilon falls linearly from 0.3 to 0.02 over the first 2400 games, and then stays at 0.02.
The log writes a record every 25 games: the mean score and win rate over that window, the current \varepsilon, and the weights4142. The last record covers the final 25 training games, played at \varepsilon = 0.02. Those games averaged 1059 points and 4 wins, a 16% win rate. They are training games and are not the benchmark.
The benchmark plays each agent on both mazes with seeds 10000 to 1019943. That is 200 games per maze and 400 per agent, and the seeds are apart from the trainer's game seeds. The same seeds replay the same games for every agent, so the comparison is fair.
| Agent | Win rate | Mean score | Mean turns | Won / lost / timeout |
|---|---|---|---|---|
| Q-learning | 59.8% | 1324.2 | 208.3 | 239 / 69 / 92 |
| Reflex | 0.0% | 111.7 | 16.9 | 0 / 399 / 1 |
| Random | 0.0% | 35.8 | 8.6 | 0 / 400 / 0 |
Q-learning wins 37.5% on Neon Lanes and 82.0% on Vault. Reflex wins no games on either maze, with mean scores of 137.3 and 86.0. The table comes from python -m pacman benchmark --games 20044.
The match runs the Q-agent on the same seeds against both ghost policies45. The learned weights were trained only against the A* ghosts, so the chance row measures how well they carry over, not what they were fitted to.
| Ghosts | Win rate | Mean score | Mean turns | Won / lost / timeout |
|---|---|---|---|---|
| AI ghosts (A* routes) | 59.8% | 1324.2 | 208.3 | 239 / 69 / 92 |
| Chance (fixed odds) | 38.0% | 1320.5 | 106.1 | 152 / 248 / 0 |
Against chance ghosts the agent wins less often and its games are shorter, while its mean score is about the same. The table comes from python -m pacman match --games 20046.