← All 10 Apps

09ProceduralHash

Seed-based world generation. 8 biomes. SHA-256.

Seed x Biome x Depth = Content. SHA-256-based deterministic generation. Same seed = same world. 8 biomes with terrain, creatures, and loot tables.

Atoms
8 biomes
Latency
~25,000ns
Size
5 KB
Use Cases
Roguelike dungeons, open world seeds, shareable level codes, procedural quests, randomized encounters
Download .py

Output

Click "Run Demo" to execute in your browser (Python runs via Pyodide)...

How It Works

How ProceduralHash Works

The lattice is a Python dict. Lookup is a hash table operation. Input keys, output values. That's the entire pattern.

Integrating With Your Engine

Unity: Call from C# via the embedded Python interpreter, or export the lattice to JSON and load it with JsonUtility.

Unreal: Use the Python plugin, or convert the Python dict to a TMap in C++.

Godot: GDScript can import Python directly, or use JSON.parse_string on the exported lattice.

Web/WASM: Pyodide runs the Python file directly in the browser. This demo page demonstrates that approach.

Extending the App

Add new entries to the lattice dictionary. The lookup function is generic: it takes any key and returns the corresponding value, or a default. The more entries you add, the more coverage you get. Performance stays O(1) regardless of size.

Key Insight

Every game logic problem that's hard-coded with if/else chains is actually a lookup table in disguise. (state, event) -> action is the universal pattern. The lattice just makes that pattern explicit and O(1).

Source Code

#!/usr/bin/env python3
"""
ProceduralHash: Seed-based generation.
Seed x Biome x Depth = Content. Deterministic. Infinite worlds. O(1).

No dependencies. Pure Python.
"""
import hashlib
import time
import struct

# === THE LATTICE: generation rules ===
BIOMES = {
    "forest":    {"terrain": ["tree", "bush", "mushroom", "grass", "fallen_log", "rock", "stream"],
                  "creatures": ["deer", "rabbit", "wolf", "bear", "sprite", "goblin"],
                  "loot": ["herb", "mushroom", "stick", "stone", "feather", "leather"],
                  "temp": 70, "moisture": 80},
    "desert":    {"terrain": ["sand_dune", "cactus", "rock", "skull", "oasis", "ruins"],
                  "creatures": ["scorpion", "snake", "vulture", "lizard", "genie"],
                  "loot": ["cactus_fruit", "gem", "ancient_coin", "bone", "glass"],
                  "temp": 110, "moisture": 10},
    "tundra":    {"terrain": ["ice", "snow", "rock", "frozen_tree", "cave", "aurora"],
                  "creatures": ["wolf", "bear", "yeti", "mammoth", "ice_sprite"],
                  "loot": ["frost_crystal", "fur", "ice_shard", "mammoth_tusk"],
                  "temp": -20, "moisture": 30},
    "swamp":     {"terrain": ["mud", "cypress", "willow", "fog", "water", "lily_pad"],
                  "creatures": ["frog", "snake", "alligator", "lizard", "witch"],
                  "loot": ["mushroom", "herb", "bone", "witch_craft", "swamp_gas"],
                  "temp": 85, "moisture": 95},
    "mountain":  {"terrain": ["rock", "cliff", "cave", "peak", "snow_cap", "goat_path"],
                  "creatures": ["goat", "eagle", "bear", "griffin", "dragon"],
                  "loot": ["gem", "ore", "dragon_scale", "ancient_relic", "gold_vein"],
                  "temp": 40, "moisture": 50},
    "ocean":     {"terrain": ["water", "wave", "island", "coral", "shipwreck", "whale_bone"],
                  "creatures": ["fish", "shark", "whale", "dolphin", "kraken"],
                  "loot": ["pearl", "coral", "fish", "shipwreck_chest", "treasure_map"],
                  "temp": 65, "moisture": 100},
    "cave":      {"terrain": ["rock", "stalagmite", "crystal", "underground_pool", "lava"],
                  "creatures": ["bat", "spider", "troll", "dragon", "demon"],
                  "loot": ["ore", "crystal", "gem", "ancient_relic", "demon_heart"],
                  "temp": 55, "moisture": 60},
    "plains":    {"terrain": ["grass", "flower", "rock", "stream", "tree_solo", "windmill"],
                  "creatures": ["deer", "horse", "rabbit", "hawk", "merchant"],
                  "loot": ["herb", "grain", "flower", "leather", "feather"],
                  "temp": 75, "moisture": 50}
}

BIOME_ICONS = {
    "forest": "\033[32m", "desert": "\033[93m", "tundra": "\033[96m", "swamp": "\033[33m",
    "mountain": "\033[90m", "ocean": "\033[94m", "cave": "\033[91m", "plains": "\033[92m"
}

def hash_to_int(seed: int, biome: str, depth: int, category: str, index: int) -> int:
    """O(1) deterministic hash. Returns int."""
    h = hashlib.sha256(f"{seed}:{biome}:{depth}:{category}:{index}".encode()).digest()
    return struct.unpack("<I", h[:4])[0]

def pick_from_list(seed: int, biome: str, depth: int, category: str, index: int) -> str:
    """O(1) pick from category list. Deterministic."""
    items = BIOMES[biome][category]
    return items[hash_to_int(seed, biome, depth, category, index) % len(items)]

def generate_chunk(seed: int, biome: str, depth: int = 0) -> dict:
    """O(1) chunk generation. Deterministic."""
    biome_data = BIOMES[biome]
    return {
        "biome": biome,
        "seed": seed,
        "depth": depth,
        "temp": biome_data["temp"] + (hash_to_int(seed, biome, depth, "temp", 0) % 21 - 10),
        "moisture": biome_data["moisture"] + (hash_to_int(seed, biome, depth, "moist", 0) % 21 - 10),
        "terrain": [pick_from_list(seed, biome, depth, "terrain", i) for i in range(6)],
        "creatures": [pick_from_list(seed, biome, depth, "creatures", i) for i in range(3)],
        "loot": [pick_from_list(seed, biome, depth, "loot", i) for i in range(4)]
    }

# === DEMO ===
def demo():
    print("=" * 50)
    print("  ProceduralHash: Seed-based world generation")
    print("=" * 50)
    print()
    print("  Generating chunks for 8 biomes, 3 depths each...")
    print()

    reset = "\033[0m"
    for biome in BIOMES:
        color = BIOME_ICONS[biome]
        print(f"  {color}[{biome.upper()}]{reset}")
        for depth in range(3):
            start = time.perf_counter_ns()
            chunk = generate_chunk(seed=42, biome=biome, depth=depth)
            elapsed = time.perf_counter_ns() - start
            print(f"    depth {depth}: T:{chunk['temp']:3d}deg F  M:{chunk['moisture']:3d}%  "
                  f"terrain:[{','.join(chunk['terrain'][:3])}...]  "
                  f"creatures:[{','.join(chunk['creatures'])}]  [{elapsed}ns]")
        print()

    print("  Determinism check: same seed = same world")
    print()
    c1 = generate_chunk(seed=42, biome="forest", depth=0)
    c2 = generate_chunk(seed=42, biome="forest", depth=0)
    print(f"    Chunk 1 creatures: {c1['creatures']}")
    print(f"    Chunk 2 creatures: {c2['creatures']}")
    print(f"    Match: {c1 == c2}")

    print()
    print("=" * 50)
    print("  8 biomes, infinite seeds, O(1) per chunk. Deterministic.")
    print("=" * 50)

if __name__ == "__main__":
    demo()