01Overview
↓
02Motivation
↓
03Approach
↓
04Implementation
↓
05Results
↓
06Challenges
↓
07What's Next
↓
← All Projects
Status Completed
Year 2022
Role Sole Author · King's College London
Stack Python 3.9 · NumPy · TKinter

01 / Project

Ghost
AI

Evaluating and improving adversarial ghost agents in Pacman using Markov Decision Processes, Deep Temporal Difference Learning, and Neuroevolutionary Genetic Algorithms.

Reinforcement LearningGenetic AlgorithmsMulti-Agent SystemsGame AI
01

Overview

This project modifies the ghost agents in a Pacman environment to make the game significantly harder to play. Four ghost variants are introduced — an algorithmically hyper-aggressive agent, an MDP-solver agent, a Deep Temporal Difference Learning agent, and a Neuroevolutionary agent — and evaluated against a deterministic autonomous Pacman baseline.

Rather than the conventional focus on building a better Pacman player, this research fills a gap in the literature by directing attention to the adversarial side: how effectively can ghost agents catch Pacman, minimise pellets collected, and deny use of power pellets? All experiments were conducted on a reduced 13×15 grid (down from the original 28×36) to manage the state space within available compute constraints.

5Ghost AI variants implemented and evaluated
1000Games sampled per experiment
203%Best metric score improvement over control group
02

Motivation

Pacman has been a popular testbed for AI research for over 15 years. Almost all prior work focuses on building an optimal Pacman-playing agent. A clear research gap exists: no study had focused on improving the adversarial ghost agents themselves. This project is, to the best of the author's knowledge, the first attempt at systematically developing and evaluating multi-agent ghost systems for the Pacman environment.

The original ghost AI operates through three alternating modes — Scatter, Chase, and Frightened — driven by hard-coded target tile algorithms unique to each of the four ghosts (Blinky, Pinky, Inky, Clyde). While ingeniously designed for gameplay balance, these deterministic rules leave significant room for improvement when the objective is purely to maximise ghost performance.

A major research gap has been found as a lot of these researches only focus on creating an agent to play the game as efficiently and effectively as possible. — Chung Tin Lo, Final Project Report (2022)

Research questions addressed

  • What is the most effective pairing of ghost AI variants to minimise Pacman's performance?
  • How do rule-based ghost agents compare to machine learning-based ghost agents in terms of catching efficiency?
  • What behavioural differences emerge between agents trained with Deep TD Learning versus Neuroevolution?
  • Does pairing two different ghost variants produce synergistic performance improvements?
03

Approach

Five ghost variants were designed and tested across a matrix of pairings. A control group (two original ORGL ghosts) established the baseline. Subsequent experiments tested each new variant individually, in combination with an original ghost, and paired against other new variants. Performance was measured across three metrics — board completion percentage, timesteps per game, and death tally — combined into a single weighted score.

1
Grid & Game Reduction

The original 28×36 Pacman grid was reduced to 13×15 (≈75% smaller) to make the state space tractable. Ghost count was halved to two and power pellets reduced from four to two, preserving core game mechanics.

2
Baseline Pacman Agents

Two deterministic Pacman agents were built to act as fair opponents: an MDP solver with a hand-crafted reward function, and a Deep TD Learning agent pre-trained on MDP agent gameplay data before live RL training.

3
Ghost Variant Design

Five ghost variants were specified: ORGL (original), AGGR (hyper-aggressive, no scatter mode), SMDP (MDP solver), DTDL (Deep TD Learning with feature extraction), and NEAT (Neuroevolutionary Augmenting Topologies).

4
Training Protocol

ML-based ghost agents were trained against the Pacman baselines with the second ghost held static, preventing interference and maximising kill-action learning opportunities. Training continued until performance plateaued.

5
Experiment Design

Twelve experiments were run — a control group plus three groups testing AGGR pairs, variant-original mixes, and variant-variant mixes. Each experiment averaged results across 1000 games. Scores were normalised against the control group.

VariantAbbr.AI TypeKey Property
OriginalORGLAlgorithmicScatter / Chase / Frightened modes
Hyper-aggressiveAGGRAlgorithmicChase mode only — no scatter
MDP SolverSMDPClassical MLValue-iteration on game grid
Deep TD LearningDTDLDeep RLANN with feature extraction + replay
NeuroevolutionaryNEATEvolutionaryBest overall — 203% improvement
04

Implementation

The project was built entirely in Python 3.9 with only NumPy (matrix operations) and TKinter (GUI) as external dependencies. The codebase is structured into agents, AI backends (deepq, mdp, neat), game components, and scripts for training, pre-training, and evaluation.

Feature vector for ML ghost agents (22 inputs for Pacman, 10 for ghosts)

  • Current valid directions — 4 binary values indicating legal moves from the current tile
  • Relative position of nearest pellet — computed via BFS from Pacman's position
  • Relative position of nearest power pellet — normalised by maximum grid distance (25)
  • Relative position and frightened state of each ghost — 5 values per ghost
Pseudocodea_star_pathfinding.py
pathfind = function(start, goal)
  openList : PriorityQueue = [start]
  closedList : List = []
  g : Map = {start: 0}
  h : Map = {start: dist(start, goal)}
  f : Map = {start: h.get(start)}
  p : Map = {start: start}

  while not openList.isEmpty()
    currentTile = openList.dequeue()
    closedList.append(currentTile)

    for each (direction, tile) of currentTile.neighbours
      if not restrictions(direction, currentTile)
        if currentTile is goal
          # reconstruct path
          path = []
          parent = goal
          while parent is not p.get(parent)
            path.append(parent)
            parent = p.get(parent)
          return path
        else
          cost = g.get(tile) + dist(currentTile, tile)
          if f.get(tile) > f
            g.put(tile, g.get(currentTile) + 1)
            h.put(tile, dist(currentTile, tile))
            f.put(tile, cost)
            p.put(tile, currentTile)

A* pathfinding drives all ghost movement, recalculated every timestep as target tiles shift. The restrictions check enforces the original game rule that ghosts cannot turn northward at four specific intersections — retained in the reduced grid (bottom two only). The NEAT variant replaces fixed weight matrices with a topological genome, with weights stored in a central lookup table keyed by connected neuron pairs.

Pseudocoderl_training_loop.py
main = function()
  game = new Game()
  action = agent.init(features(game))
  epochs = 0

  while epochs < epochLimit
    game.nextStep(action)
    if game.over or game.won
      epochs = epochs + 1
      agent.end(reward(game))
      game = new Game()
      action = agent.init(features(game))
    else
      action = agent.step(features(game), reward(game))
ConditionReward Value
Default step−0.5
Stationary−10
Ate a pellet+20
Ate a power pellet+3
Ate a ghost+50
Loss−20 × remaining pellets
Win+2000

Ghost pathfinding visualisation — A* routes shown as coloured lines from each ghost to Pacman

Fig. 1 — Ghost pathfinding on the reduced 13×15 grid. Coloured lines trace each ghost's A* route to its target tile, recalculated every timestep.

05

Results

Every new ghost variant combination outperformed the control group across the combined metric score. The best-performing pairing was NEAT + ORGL, achieving a 203% improvement — statistically making the game twice as hard for the autonomous Pacman agent. All ML-based variants achieved an average death tally of zero, demonstrating a complete ability to evade power-pellet retaliation.

ExperimentGhost 1Ghost 2Completion %TimestepsDeathsNormalised Score
ControlORGLORGL61.71103.960.111.00
1AGGRAGGR42.8961.650.471.48
2.1AGGRORGL46.0355.490.441.43
2.2SMDPORGL43.4953.220.001.49
2.3DTDLORGL19.7858.140.001.95
2.4NEATORGL18.7732.840.002.03
3.1AGGRSMDP30.9275.750.471.68
3.2AGGRDTDL34.4035.380.311.71
3.3AGGRNEAT38.54135.020.511.38
3.4SMDPDTDL30.27122.040.001.58
3.5SMDPNEAT27.15113.170.001.67
3.6DTDLNEAT20.31112.420.001.80

Key findings

  1. NEAT + ORGL was the single best pairing, reducing board completion to 18.77% and timesteps to 32.84 — the lowest of any experiment.
  2. All ML-based pairings (experiments 2.2–2.4, 3.4–3.6) achieved 0 average deaths, completely neutralising Pacman's power-pellet mechanic.
  3. AGGR + NEAT (3.3) was the worst-performing new combination (1.38×), largely due to stalemate states inflating timestep counts past the 200-step cutoff.
  4. Hyper-aggressive (AGGR) pairings excel at reducing completion percentage but carry high death tallies — a high-risk, high-reward profile.
  5. Machine learning ghosts paired against each other cause stalemate loops, an emergent failure mode requiring reward reshaping in future work.
06

Challenges

Three core limitations constrained the generalisability and scope of the findings, each rooted in the practical realities of a solo undergraduate project completed on personal hardware within a semester-length timeline.

Limited computational power

All training was performed on personal hardware. The grid had to be reduced from 28×36 to 13×15 to keep episode lengths and convergence times manageable. This prevents direct generalisation of results to the full Pacman game, where the larger state space would demand significantly more training time and GPU resources.

Lack of human player data

ML ghost agents were trained exclusively against deterministic Pacman baselines. The agents appear to exploit fixed patterns in the baseline's movement rather than learning general pursuit strategies. When tested informally against human players, the learnt behaviours did not transfer — the ghosts exhibited erratic movement unable to exploit the non-deterministic patterns of a human. Attempts to retrain on human gameplay were abandoned as infeasible within the project timeline.

Imperfect reward shaping causing stalemate loops

When two ML-based ghosts face each other, their individually optimal policies can lock the game into a looping stalemate where no progress is made. A fail-safe auto-terminates games at 200 timesteps, but this inflates the timestep metric artificially. The current reward function inadvertently incentivises the looping behaviour and would need to be reshaped to penalise stalemate states explicitly.

07

What's Next

The findings open several concrete directions for extending this work, ranging from data collection improvements to architectural changes that would allow agents to generalise beyond the reduced grid and the deterministic baseline opponent.

  • Retrain ML ghost agents on human gameplay data — either by pre-training on recorded expert games or deploying the agents in a live setting where they learn from real players — to overcome the deterministic-baseline exploitation problem.
  • Introduce convolutional or recurrent layers so agents can learn directly from the raw game grid rather than hand-crafted features, enabling richer spatial and temporal reasoning.
  • Reshape the reward function to penalise stalemate states, eliminating the artificial inflation of timestep metrics and producing cleaner comparisons between variant pairings.
  • Scale experiments back to the original 28×36 grid with full GPU compute, validating whether the relative performance rankings hold at the true game scale.
  • Introduce cooperative multi-agent training so ghost pairs learn to coordinate coverage of the grid rather than independently converging on identical pursuit paths.