← MAIN
07 // ROUTE SEARCH AND LEARNING

PAC-MAN

Eat every pellet and avoid the ghosts. A learned agent scores each move, and its scores are shown on the board.
SCORE 0 PELLETS — TURN 0 STATUS READY

HOW TO PLAY

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.

Use W A S D or the arrow keys to move. Each key is one turn.
Move log
MATCH
MODE
MAZE
AGENT
GHOSTS
SCORE (watch games, same settings)
BRAIN
Watch the Q-learning agent to see its value for each move.
    GHOSTS
    LEARNED WEIGHTS
    Loading the learned weights…
      More settings
      SEED (same seed, same ghosts)
      SPEED

      HOW IT WORKS

      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 rules

      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.

      4
      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

      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.

      Route search with A*

      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.

      f(n) = g(n) + h(n), \qquad h(n) = |r_n - r_{\text{goal}}| + |c_n - c_{\text{goal}}|
      5

      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.

      5
      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

      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.

      Ghost personalities and targets

      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.

      • Chaser targets Pac-Man's cell.
      • Ambusher targets the cell 4 steps ahead of Pac-Man in his last direction, walking forward and stopping early at a wall9.
      • Scatter targets Pac-Man's cell, unless its Manhattan distance to him is at most 4. Then it targets its corner: the open cell nearest one of the four corners, chosen by index10.

      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.

      11
      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

      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.

      Chance ghosts (fixed odds)

      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.

      P(d) = \dfrac{o\big((d - h) \bmod 4\big)}{\sum_{d' \in D} o\big((d' - h) \bmod 4\big)}
      14

      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.

      14
      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

      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.

      Reflex rule (baseline)

      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

      R(a) = \begin{cases} -1000 & \text{an active ghost stands on the destination} \\ -\sum_{d \in \{1, 2\}} 40\,(3 - d) \;+\; 50\,\mathbf{1}_{\text{scared}} \;-\; \text{food}(a) & \text{otherwise} \end{cases}
      17

      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.

      17
      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

      Random agent (floor)

      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.

      Features and the learned weights

      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:

      Q(s, a) = w \cdot f(s, a) = \sum_{i=1}^{13} w_i \, f_i(s, a)
      1920

      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.

      \text{food} = \frac{d_{\text{pellet}}}{10}, \qquad \text{capsule} = \frac{d_{\text{power}}}{10}, \qquad \text{ghost\_near} = \sum_{g \text{ active}} \max\!\left(0,\, 1 - \frac{d_g}{6}\right)
      23
      \text{scared\_near} = \sum_{\substack{g \text{ scared} \\ d_g \ge 1}} \max\!\left(0,\, 1 - \frac{d_g}{8}\right), \qquad \text{openness} = \frac{n_{\text{open}}}{4}, \qquad \text{trap} = \text{ghost\_near} \cdot (1 - \text{openness})
      24

      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.

      FeatureWhat it measuresLearned weight
      biasConstant 1. Learns the typical value of a turn.-236.366284
      pellet1 if the move eats a pellet.5.970195
      power1 if the move eats a power pellet.39.047522
      foodWalking distance to the nearest pellet, / 10 (0 when none remains).-69.462897
      capsuleWalking distance to the nearest power pellet, / 10 (0 when none remains).-21.996608
      ghost_nearSum over active ghosts of max(0, 1 - d / 6), d = walking distance from the move.-17.705702
      ghost_adjacent1 if an active ghost is one step from the move.-3.078364
      caught1 if an active ghost stands on the destination (fatal).8.172549
      scared_nearSum over scared ghosts of max(0, 1 - d / 8), for d at least 1.9.023088
      eat_ghost1 if the move lands on a scared ghost.76.037818
      opennessOpen neighbours of the destination, / 4. Low values are dead ends.5.848713
      trapghost_near × (1 - openness): a ghost closing in on a dead end.10.632794
      survivalTurns 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

      Survival lookahead (one feature)

      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.

      \text{survival}(s, a) = \frac{D(s, a)}{H}, \qquad D(s, a) = \begin{cases} 0 & \text{the move is fatal} \\ 1 + A(s_a, H - 1) & \text{otherwise} \end{cases}
      2627
      A(x, p) = \begin{cases} p & p = 0 \text{ or } x \text{ is over} \\ \max\!\Big(\{0\} \cup \{\,1 + A(x_{a'}, p - 1) : a' \text{ not fatal}\,\}\Big) & \text{otherwise} \end{cases}
      28

      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.

      31
      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

      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.

      Approximate Q-learning

      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:

      \begin{aligned} \text{target} &= r + \gamma \max_{a'} Q(s', a') \qquad (\text{target} = r \text{ when the game ended}) \\ \delta &= \text{target} - Q(s, a) \\ w_i &\leftarrow w_i + \alpha\, \delta\, f_i(s, a) \end{aligned}
      32

      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.

      r = \text{points} - 1 - 300 \cdot \mathbf{1}_{\text{caught}}
      34

      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.

      36
      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

      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.

      Training

      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.

      \alpha_{ep} = \alpha_{\text{start}} + (\alpha_{\text{end}} - \alpha_{\text{start}})\,\frac{ep}{N - 1}, \qquad \varepsilon_{ep} = \varepsilon_{\text{start}} + (\varepsilon_{\text{end}} - \varepsilon_{\text{start}})\,\min\!\left(1,\, \frac{ep}{0.8\,N}\right)
      40

      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.

      Results on fixed seeds

      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.

      AgentWin rateMean scoreMean turnsWon / lost / timeout
      Q-learning59.8%1324.2208.3239 / 69 / 92
      Reflex0.0%111.716.90 / 399 / 1
      Random0.0%35.88.60 / 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.

      GhostsWin rateMean scoreMean turnsWon / lost / timeout
      AI ghosts (A* routes)59.8%1324.2208.3239 / 69 / 92
      Chance (fixed odds)38.0%1320.5106.1152 / 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.