Worlds, AI and multiplayer · 7 MIN READ

A* on a grid: a heap, a heuristic that matches the moves, and tie-breaking you can replay

Implement grid A* with container/heap, choose a heuristic that matches the movement rules, make equal-cost choices deterministic and decide when a flow field beats per-unit searches.

Chasing the player in a straight line works until the first wall. Breadth-first search finds a way around but ignores terrain cost; Dijkstra respects cost but explores every cell closer than the goal, in all directions. A* keeps Dijkstra's guarantee while steering the search with an estimate of the remaining distance. Its quality depends on three choices that are easy to get subtly wrong: the cost model, the heuristic and the tie-break.

gamedev · A MAP OF THE IDEA

  1. Push start, h to goal
  2. Pop lowest f, h, seq
  3. Relax open neighbors
  4. Rebuild from parents

Useful when

  • Optimal paths with far fewer expansions than Dijkstra.
  • Integer costs and a total order make results replayable.

Watch out

  • Manhattan on an 8-way grid overestimates and loses optimality.
  • An unreachable goal explores every reachable cell; budget it.

Implementation & operation cost: A heap, two arrays sized to the map and a careful Less method; time grows with the cells expanded times the log of the open-set size.

01

What A* tracks and what it guarantees

For each cell A* tracks g, the cheapest known cost from the start, and h, an estimate of the cost from the cell to the goal. The open set is a priority queue ordered by f = g + h; the search repeatedly expands the lowest-f cell and relaxes its neighbors. If h never overestimates the true remaining cost, it is admissible, and the first time the goal leaves the queue its path is optimal. With h = 0, A* is Dijkstra; a larger admissible h expands fewer cells. The pathfinder should not own the map. It asks a walkability question per cell, so the same search can run against static walls, a door table or a temporary obstacle overlay. Use integer costs, 10 per straight step and 14 per diagonal, so sums are exact and comparisons cannot depend on floating-point rounding.

02

A* with container/heap and a total order

The program parses a small ASCII level, runs a 4-way search with the Manhattan heuristic and an 8-way search with the octile heuristic, and draws each path with asterisks. It then runs the 8-way search with a zero heuristic to compare the work done, and finally seals both gaps in the central wall to show what an unreachable goal costs.

go
package main

import (
	"container/heap"
	"fmt"
	"math"
	"strings"
)

type Point struct{ X, Y int }

type Grid struct {
	W, H  int
	walls []bool
}

func ParseGrid(rows []string) (g Grid, start, goal Point) {
	g = Grid{W: len(rows[0]), H: len(rows), walls: make([]bool, len(rows[0])*len(rows))}
	for y, row := range rows {
		for x, ch := range row {
			switch ch {
			case '#':
				g.walls[y*g.W+x] = true
			case 'S':
				start = Point{x, y}
			case 'G':
				goal = Point{x, y}
			}
		}
	}
	return g, start, goal
}

func (g Grid) Open(p Point) bool {
	return p.X >= 0 && p.Y >= 0 && p.X < g.W && p.Y < g.H && !g.walls[p.Y*g.W+p.X]
}

// Costs are integers: 10 per straight step, 14 per diagonal (about 10*sqrt2).
const straight, diagonal = 10, 14

type Heuristic func(a, b Point) int

func Manhattan(a, b Point) int { return straight * (abs(a.X-b.X) + abs(a.Y-b.Y)) }

func Octile(a, b Point) int {
	dx, dy := abs(a.X-b.X), abs(a.Y-b.Y)
	return straight*max(dx, dy) + (diagonal-straight)*min(dx, dy)
}

func abs(v int) int {
	if v < 0 {
		return -v
	}
	return v
}

// node ordering is total: lowest f, then lowest h, then oldest push.
type node struct {
	p    Point
	g, h int
	seq  int
}

type openSet []*node

func (o openSet) Len() int { return len(o) }
func (o openSet) Less(i, j int) bool {
	a, b := o[i], o[j]
	if a.g+a.h != b.g+b.h {
		return a.g+a.h < b.g+b.h
	}
	if a.h != b.h {
		return a.h < b.h
	}
	return a.seq < b.seq
}
func (o openSet) Swap(i, j int) { o[i], o[j] = o[j], o[i] }
func (o *openSet) Push(x any)   { *o = append(*o, x.(*node)) }
func (o *openSet) Pop() any {
	old := *o
	n := old[len(old)-1]
	*o = old[:len(old)-1]
	return n
}

// Fixed neighbor order: E, S, W, N, then diagonals SE, SW, NW, NE.
var steps = []Point{{1, 0}, {0, 1}, {-1, 0}, {0, -1}, {1, 1}, {-1, 1}, {-1, -1}, {1, -1}}

func FindPath(g Grid, start, goal Point, diagonals bool, h Heuristic) (path []Point, cost, expanded int) {
	dirs := steps[:4]
	if diagonals {
		dirs = steps
	}
	best := make([]int, g.W*g.H) // cheapest known g per cell
	for i := range best {
		best[i] = math.MaxInt
	}
	from := make([]Point, g.W*g.H)
	open := &openSet{}
	seq := 0
	heap.Push(open, &node{p: start, h: h(start, goal)})
	best[start.Y*g.W+start.X] = 0
	for open.Len() > 0 {
		cur := heap.Pop(open).(*node)
		if cur.g != best[cur.p.Y*g.W+cur.p.X] {
			continue // stale entry: a cheaper route was pushed later
		}
		expanded++
		if cur.p == goal {
			for p := goal; p != start; p = from[p.Y*g.W+p.X] {
				path = append(path, p)
			}
			path = append(path, start)
			for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 {
				path[i], path[j] = path[j], path[i]
			}
			return path, cur.g, expanded
		}
		for _, d := range dirs {
			next := Point{cur.p.X + d.X, cur.p.Y + d.Y}
			if !g.Open(next) {
				continue
			}
			step := straight
			if d.X != 0 && d.Y != 0 {
				// No corner cutting: both orthogonal cells must be open.
				if !g.Open(Point{cur.p.X + d.X, cur.p.Y}) || !g.Open(Point{cur.p.X, cur.p.Y + d.Y}) {
					continue
				}
				step = diagonal
			}
			ng := cur.g + step
			i := next.Y*g.W + next.X
			if ng >= best[i] {
				continue
			}
			best[i], from[i] = ng, cur.p
			seq++
			heap.Push(open, &node{p: next, g: ng, h: h(next, goal), seq: seq})
		}
	}
	return nil, 0, expanded
}

func Render(rows []string, path []Point) []string {
	out := make([][]byte, len(rows))
	for y, row := range rows {
		out[y] = []byte(row)
	}
	for _, p := range path {
		if out[p.Y][p.X] == '.' {
			out[p.Y][p.X] = '*'
		}
	}
	lines := make([]string, len(out))
	for y := range out {
		lines[y] = string(out[y])
	}
	return lines
}

func main() {
	rows := []string{
		"S....#........",
		".##..#..####..",
		"..#..#.....#..",
		"..#.....#..#..",
		"..####..#..##.",
		"........#....G",
	}
	g, start, goal := ParseGrid(rows)
	for _, run := range []struct {
		name      string
		diagonals bool
		h         Heuristic
		draw      bool
	}{
		{"4-way, Manhattan", false, Manhattan, true},
		{"8-way, octile", true, Octile, true},
		{"8-way, zero (Dijkstra)", true, func(a, b Point) int { return 0 }, false},
	} {
		path, cost, expanded := FindPath(g, start, goal, run.diagonals, run.h)
		fmt.Printf("%s: %d steps, cost %d, expanded %d\n", run.name, len(path)-1, cost, expanded)
		if run.draw {
			fmt.Println(strings.Join(Render(rows, path), "\n"))
		}
	}
	for _, p := range []Point{{8, 0}, {8, 2}} {
		g.walls[p.Y*g.W+p.X] = true // seal both gaps in column 8
	}
	path, _, expanded := FindPath(g, start, goal, true, Octile)
	fmt.Printf("gaps sealed: path found %t, expanded %d\n", path != nil, expanded)
}
Read the code

openSet implements heap.Interface, and heap.Push and heap.Pop keep it ordered by Less, which compares f, then h, then a sequence number assigned at push time, so no two entries ever compare equal. Instead of a decrease-key operation, a cheaper route simply pushes a new entry; when the outdated entry surfaces later, its g no longer matches best and it is skipped. A diagonal step is allowed only when both orthogonal neighbors are open, so a path never squeezes between two diagonal walls. The 4-way path costs 200 over 20 steps; diagonals cut it to 182 over 17. The zero heuristic finds the same cost but expands 57 cells instead of 43. With both gaps sealed, the search exhausts all 37 reachable cells before it can report that no path exists.

03

The heuristic must match the movement rules

Manhattan distance, 10*(dx+dy), is exact on an empty 4-way grid and admissible with walls. On an 8-way grid it overestimates: one diagonal step costs 14, but Manhattan charges 20, so the search can return a path that is not the cheapest. Octile distance, 10max(dx,dy) + 4min(dx,dy), is exact on an empty 8-way grid. Euclidean distance is admissible for both but underestimates, so it expands more cells than octile for no benefit on a grid. If some terrain costs less than 10 per step, such as roads, scale the heuristic by the cheapest step cost or it stops being admissible. An inadmissible heuristic is sometimes a deliberate choice: multiplying an admissible h by 1.2 finds paths faster and guarantees a result at most 20 percent longer than optimal, a trade many games accept for background units. Make that a named weight, not an accident of mixing movement rules.

04

Tie-breaking is part of the result

On a grid many paths share the same cost, so the order of equal-f entries decides which path you get. A binary heap is not stable: entries that compare equal leave in whatever order the heap happens to hold them. The search is still repeatable for one fixed sequence of pushes, but a harmless-looking refactor, such as generating neighbors in another order, reusing a heap between searches or reading blocked cells from a map, silently changes the chosen route. That breaks golden tests, replays that rerun the simulation from recorded inputs, and any lockstep network model where peers must agree. A total order fixes it: lower f first; among equal f, lower h, which prefers entries closer to the goal and usually expands fewer cells; then the push sequence number. Keep the neighbor order in a fixed slice, never a map, and write the ordering rule in a comment, because the chosen path is now part of the contract.

05

Many units, one goal: cache paths or build a flow field

A* answers one start for one goal. Thirty units converging on a base would run thirty searches over nearly the same cells. A flow field inverts the problem: one breadth-first or Dijkstra pass outward from the goal records, for every reachable cell, the neighbor one step closer, so each unit just follows next[cell] each tick. Its cost scales with the map, not with the number of units, and units spawned anywhere are handled for free. Rebuild it when the goal moves or walls change. For a few long-lived units with different goals, cache A* results keyed by start, goal and a map version counter that increments on every wall change, and revalidate a cached path lazily when its next step becomes blocked. When a search is expensive, give it a budget of expansions per tick and resume it on the next tick rather than letting one search consume the frame.

go
// BuildFlowField runs one breadth-first search outward from the goal.
// next[i] is the neighbor one step closer to the goal; dist[i] < 0 means
// the cell cannot reach the goal at all.
func BuildFlowField(g Grid, goal Point) (next []Point, dist []int) {
	next = make([]Point, g.W*g.H)
	dist = make([]int, g.W*g.H)
	for i := range dist {
		dist[i] = -1
	}
	dist[goal.Y*g.W+goal.X] = 0
	queue := []Point{goal}
	for len(queue) > 0 {
		cur := queue[0]
		queue = queue[1:]
		for _, d := range steps[:4] {
			n := Point{cur.X + d.X, cur.Y + d.Y}
			if !g.Open(n) || dist[n.Y*g.W+n.X] >= 0 {
				continue
			}
			dist[n.Y*g.W+n.X] = dist[cur.Y*g.W+cur.X] + 1
			next[n.Y*g.W+n.X] = cur
			queue = append(queue, n)
		}
	}
	return next, dist
}
Read the code

This fragment reuses Grid, Point and the steps slice from the program above; paste it below FindPath and call it from main to run it in your own native environment. It is a breadth-first search, so it assumes every step costs the same; weighted terrain needs the same loop driven by a heap, as in A*. dist doubles as the visited set and as the answer to whether a unit can reach the goal at all. That matters because the zero value of next would otherwise point every unreachable unit at cell (0,0). On the lesson level it reports a distance of 20 steps from S, matching the 4-way A* path.

06

Test the search, not the screenshot

Keep golden ASCII fixtures like the ones printed above and compare the rendered path, its cost and the expansion count; a jump in expansions exposes a broken heuristic even when the path still looks right. Check that a start equal to the goal returns a one-cell path, that a goal inside a wall or behind a sealed wall returns no path, and that every returned path is contiguous, avoids walls and costs exactly the sum of its steps. For optimality, generate many seeded random maps and assert that the A* cost equals the zero-heuristic cost. Benchmark the worst case, an unreachable goal on the largest map, because that search explores everything; decide in game design whether units should even try, or should first check a cheap connectivity label for the two regions.

TAKE THIS WITH YOU

Use an admissible heuristic that matches the movement rules, give the open set a total order so equal-cost choices are reproducible, and switch to one shared flow field when many units travel to the same goal.

Check your understanding

Two routes to the goal have the same cost. What makes an A* implementation keep choosing the same one after a refactor?

Go to the source

Progress stays in this browser. No account needed.