Skip to main content

TownForge v1.0.0

TownForge is a customizable Python library for generating procedural town maps for games and simulations.

Generate towns with randomized building sizes, configurable building types, spacing, and door placement. Use the tile map and building metadata in your own game, or export a PNG preview.

Originally developed as part of TerraForge, TownForge is now being packaged as a standalone library. Its code requires NumPy and Pillow; it does not require TerraForge or the noise library.

Features

  • Procedural square town maps stored as NumPy arrays
  • Custom building types, colors, size ranges, and quantity ranges
  • Placement priorities for important buildings
  • Building overlap prevention with configurable spacing
  • Configurable padding around the map edges
  • Randomized doors with selectable building sides and corner inset
  • Building metadata and coordinate lookup helpers
  • PNG export with optional building labels
  • Seeded generation for reproducible layouts

Installation

Once the standalone package is published on PyPI under the name townforge, install it with:

python -m pip install townforge

The package should install its required dependencies automatically:

  • NumPy
  • Pillow

If you are using the source files directly, install the dependencies yourself:

python -m pip install numpy pillow

The examples below use from townforge import TownForge.

Quick Start

from townforge import TownForge

generator = TownForge(
    map_size=300,
    image_size=(900, 900),
    seed=42,
)

town_map = generator.generate()
generator.export_town_map_image()

print("Map shape:", town_map.shape)
print("Buildings placed:", len(generator.buildings))

This creates a 300 × 300 tile town and saves a 900 × 900 pixel preview as town_map.png in the current directory.

The default building types are houses, shops, taverns, temples, guildhalls, and castles. Castles have a default quantity range of zero to one, so not every town includes one.

Working With the Tile Map

generate() returns a two-dimensional NumPy array with these tile values:

Constant Value Meaning
TownForge.GROUND 0 Ground outside buildings
TownForge.BUILDING 1 Building footprint
TownForge.DOOR 2 Door tile on a building edge

Access tiles using town_map[y, x], while building lookup methods accept (x, y):

x, y = 10, 20
tile = town_map[y, x]

if tile == TownForge.GROUND:
    print("Ground")
elif tile == TownForge.BUILDING:
    print("Building")
elif tile == TownForge.DOOR:
    print("Door")

Building footprints are filled rectangles. TownForge does not generate separate interiors or define movement rules; your game decides how these tiles behave.

Custom Building Types

Pass a dictionary to building_types to replace the default building types:

from townforge import TownForge

building_types = {
    "house": {
        "name": "House",
        "color": "#8B5A2B",
        "size": (8, 14),
        "min_quantity": 15,
        "max_quantity": 30,
        "priority": 1,
    },
    "blacksmith": {
        "name": "Blacksmith",
        "color": "#708090",
        "size": (10, 16),
        "min_quantity": 1,
        "max_quantity": 3,
        "priority": 10,
    },
    "guildhall": {
        "name": "Courier's Guild",
        "color": "#556B2F",
        "size": (18, 24),
        "min_quantity": 1,
        "max_quantity": 1,
        "priority": 50,
    },
}

generator = TownForge(
    building_types=building_types,
    map_size=200,
    image_size=800,
    seed=42,
    building_padding=4,
)

town_map = generator.generate()
generator.export_town_map_image(show_building_names=True)
Field Description
Dictionary key Building type identifier, such as "house" or "blacksmith"
name Display name used in metadata and optional image labels
color Building fill color for PNG export
size Inclusive (minimum, maximum) range; width and height are sampled independently
min_quantity Minimum requested count for this type
max_quantity Maximum requested count for this type
priority Optional placement priority, defaulting to 0; higher values are processed first

Quantity ranges specify requested counts, not guaranteed placement counts. A crowded map may contain fewer buildings when the placement attempt limit is reached.

Generator Options

Parameter Default Description
building_types None Custom building definitions; None uses the defaults
map_size 300 Width and height of the square tile map
seed None Seed for the generator's local random number generator
image_size None Export size in pixels: an integer for a square, or (width, height); None uses the map dimensions
building_padding 4 Minimum spacing between building footprints, in tiles
ground_color "#3E7C3C" Ground color in the exported image
door_color "#FFD700" Door color in the exported image
outline_color "black" Building outline color in the exported image
max_failures_multiplier 20 Failed placement budget per type: requested quantity multiplied by this value
door_sides ("north", "south", "east", "west") Sides eligible for door placement
map_edge_padding 5 Minimum distance between buildings and the map boundary, in tiles
door_inset 1 Door offset from corners along the chosen edge, in tiles

For example, to place doors only on north and south edges:

generator = TownForge(
    seed=42,
    door_sides=("north", "south"),
    door_inset=1,
    map_edge_padding=10,
)
town_map = generator.generate()

Choose building dimensions that fit inside map_size - 2 * map_edge_padding. Door inset must also fit the building dimensions: use a minimum dimension of at least 2 * door_inset + 1. Supply a nonempty door_sides sequence containing valid side names.

Accessing Building Data

After generation, generator.buildings contains a list of building dictionaries:

for building in generator.buildings:
    print(building["id"], building["name"], building["door"])

Each dictionary contains:

Key Meaning
id Instance identifier, such as "house_0"
type Building type key, such as "house"
name Display name
x, y Top-left tile coordinates
width, height Building dimensions in tiles
color Export fill color
door Door coordinate tuple (x, y)

Find a Building at a Tile

building = generator.get_building_at(x=10, y=20)

if building is not None:
    print(building["name"])

Returns the building whose footprint includes the coordinate, including its door tile, or None if no building occupies it.

Find a Building by Its Door

if generator.buildings:
    door_x, door_y = generator.buildings[0]["door"]
    building = generator.get_building_by_door(door_x, door_y)
    print("Entered:", building["name"])

Returns the building with that exact door coordinate, or None. This can connect door tiles to shops, guilds, interiors, or other interactions in your game.

Exporting a PNG

Call generate() before exporting. Create your output directory first:

from pathlib import Path
from townforge import TownForge

output_dir = Path("generated_maps")
output_dir.mkdir(parents=True, exist_ok=True)

generator = TownForge(seed=42, image_size=(1200, 1200))
generator.generate()
generator.export_town_map_image(
    output_dir=str(output_dir),
    show_building_names=True,
    building_name_color="white",
)

This saves generated_maps/town_map.png. Exporting again to the same directory overwrites that file. Image size affects only the preview resolution, not the tile map dimensions.

Reproducible Towns

Create a new generator with the same seed and settings to reproduce a layout:

from townforge import TownForge
import numpy as np

first = TownForge(seed=123, map_size=300)
second = TownForge(seed=123, map_size=300)

assert np.array_equal(first.generate(), second.generate())

Calling generate() repeatedly on the same instance advances its random generator and can produce different towns. To recreate the original town, construct a new instance with the original seed and settings. Exact layouts are not guaranteed to remain identical across future library versions.

License

TownForge is released under the MIT License.

Copyright © 2026 Brianna Ladson.

Metadata

Release files for townforge 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for townforge 1.0.0
File Size Uploaded Provenance Actions
townforge-1.0.0.tar.gz 8.3 kB Without provenance Details for townforge-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for townforge 1.0.0
File Interpreter ABI Platform Actions
townforge-1.0.0-py3-none-any.whl Python 3 none any Details for townforge-1.0.0-py3-none-any.whl

Total release size: 15.4 kB

Release files / townforge-1.0.0.tar.gz

Download URL townforge-1.0.0.tar.gz
Size 8.3 kB
Tags Source
SHA-256 checksum
How to use checksums
586037cfede91bdda5a3a239f973c52645b6878715249e37705ab0ca16792cb1
BLAKE2b-256 checksum
How to use checksums
3c3ba1964ac07f4795471862f748f9bac50650f93b2956463c2bb6763c0f6301
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.7

Release files / townforge-1.0.0-py3-none-any.whl

Download URL townforge-1.0.0-py3-none-any.whl
Size 7.0 kB
Tags Python 3
SHA-256 checksum
How to use checksums
12ef7b3a5f6d5242a5e9d4b61475566aa594e78d350d2d824c8a5826e2c21c48
BLAKE2b-256 checksum
How to use checksums
6c8809fbcf843126822a880bd5efbdf0e8f1c9fd1019af700a746f6ecda2cb4d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.7

Security for townforge 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page