Metadata-Version: 2.4
Name: townforge
Version: 1.0.0
Summary: A customizable procedural town map generator for games and simulations.
Author: Brianna Ladson
License-Expression: MIT
Keywords: procedural-generation,town,maps,games,simulation
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Games/Entertainment
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: numpy
Requires-Dist: Pillow

# 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](https://github.com/BriannaLadson/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:

```bash
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:

```bash
python -m pip install numpy pillow
```

The examples below use `from townforge import TownForge`.

## Quick Start

```python
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)`**:

```python
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:

```python
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:

```python
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:

```python
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

```python
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

```python
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:

```python
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:

```python
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](LICENSE).

Copyright © 2026 Brianna Ladson.
