К основному содержанию
скилл Claude Code CX Codex Cursor GitHub Copilot

procedural-gen — скилл для Claude Code: что делает и как установить

Генерирует уровни и таблицы лута по сиду на основе детерминированных алгоритмов. Пригодится для процедурного контента без ручной расстановки.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill procedural-gen -a claude-code
Открыть на GitHub

Что делает procedural-gen

Скилл даёт правила для генерации уровней и наград. В основе лежит детерминизм. Один сид всегда воспроизводит одинаковый мир. Так проще повторять баги при отладке. Скилл запрещает вызывать глобальный генератор случайных чисел. Код передаёт выделенный экземпляр генератора во все функции.

Генерация сначала заполняет сырые структуры данных вроде массивов или словарей. Никакой привязки к рендерингу нет. Чтобы превратить матрицу в готовую карту тайлов, понадобятся отдельные инструменты движка для Godot или Unity. Это разделение исключает путаницу между математикой мира и графикой.

Скилл включает проверку связности через алгоритм заливки и таблицы вероятностей лута. Вызовы функций не зависят от игрового движка. При настройке важно фиксировать сид, чтобы оценивать влияние каждого параметра отдельно.

Какие задачи решает

  • генерировать подземелья с комнатами и коридорами
  • вычислять карты высот алгоритмами фрактального шума
  • рассчитывать вероятности выпадения предметов через весовые таблицы
  • проверять проходимость и связность комнат заливкой

Примеры запросов агенту

  • Сделай генератор подземелий с комнатами и коридорами на базе сида
  • Напиши функцию фрактального шума для карты высот острова
  • Создай весовую таблицу лута с детерминированным генератором

Как установить procedural-gen

1Через Skills CLI (Vercel)

npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill procedural-gen -a claude-code

2Вручную: положить файлы

~/.claude/skills/procedural-gen/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/procedural-gen/

Из того же набора40

Весь набор →
game-feel gamedev-skills Скилл учит агента добавлять отклик к игровым действиям: тряску камеры, стоп-кадр, твины с easing, сквош и отброс. Для случаев, когда механика работает, но ощущается ватной. Claude Code CX Codex Cursor +1 9 400установок game-ui-ux gamedev-skills Архитектурный скилл для создания адаптивных игровых интерфейсов, стека экранов и навигации с геймпада без покадрового опроса состояния. Claude Code CX Codex Cursor +1 9 200установок level-design gamedev-skills Помогает спроектировать игровой уровень от блокута до плейтеста: маршруты, темп, препятствия и столкновения. Нужен при работе с whitebox, критическим путём и геймплейными комнатами. Claude Code CX Codex Cursor +1 7 500установок camera-systems gamedev-skills Рецепты для игровых камер в 2D и 3D: плавное следование, мёртвые зоны, опережение движения и обработка столкновений для Godot и Unity. Claude Code CX Codex Cursor +1 7 100установок audio-design gamedev-skills Скилл учит раскладывать игровой звук по шинам, глушить музыку под голос и собирать адаптивный саундтрек слоями. Примеры кода — на GDScript под Godot 4.7, с пометками для Unity. Claude Code CX Codex Cursor +1 7 100установок performance-optimization gamedev-skills Скилл учит искать узкое место в игре по профайлеру движка, а не по догадке, и даёт набор правок: пулы объектов, батчинг, отказ от лишних аллокаций. Claude Code CX Codex Cursor +1 7 100установок game-ai gamedev-skills Помогает проектировать логику врагов и NPC: конечные автоматы, деревья поведения, алгоритмы руления и поиск пути A*. Пригодится при сборке поведения ботов для любого движка. Claude Code CX Codex Cursor +1 7 100установок input-systems gamedev-skills Архитектура игровых управлений: отображение клавиш на действия, перекоординирование с проверкой конфликтов, поддержка клавиатуры, геймпада и сенсора, мёртвые зоны, буферизация и coyote time. Claude Code CX Codex Cursor +1 6 800установок

Похожие

unity-developer rmyndharis Скилл для разработки игр на Unity 6 LTS с оптимизацией производительности, настройкой конвейеров рендеринга и кроссплатформной сборкой. Помогает писать C# код, настраивать URP/HDRP и решать проблемы с физикой и ассетами. Claude Code CX Codex Cursor +1 3 000установок orbit-card heygen-com Скилл для встраивания готового 10-секундного 3D-блока HyperFrames: карточка фичи облетает сферу из точек по траектории камеры из Blender. Claude Code CX Codex Cursor +1 9 800установок sdf earthtojake Скилл создаёт и проверяет SDFormat-файлы для моделей и миров, а затем помогает подготовить их к передаче в симулятор. Claude Code CX Codex Cursor +1 10 500установок urdf earthtojake Скилл помогает создавать, проверять и отлаживать описания роботов в формате URDF. Пригодится для работы со звеньями, сочленениями и геометрией. Claude Code CX Codex Cursor +1 10 400установок hatch-pet официальный openai Создаёт и упаковывает анимированных питомцев и спрайт-листы для Codex. Пригодится, когда нужен персонаж по описанию, изображению или фирменным ориентирам. Claude Code CX Codex Cursor +1 3 300установок gcode earthtojake Нарезает модели STL, 3MF и OBJ в G-code через OrcaSlicer. Подходит, когда нужно подготовить файл для печати без подключения к принтеру. Claude Code CX Codex Cursor +1 9 500установок dxf earthtojake Скилл собирает и проверяет 2D DXF-чертежи из Python-скриптов на build123d: контуры, прокладки, панели, развёртки под лазер. Claude Code CX Codex Cursor +1 9 100установок

Вопросы о procedural-gen

Как установить procedural-gen в Claude Code?

Выполните команду npx skills add gamedev-skills/awesome-gamedev-agent-skills --skill procedural-gen -a claude-code.

Что делает скилл procedural-gen?

Скилл содержит алгоритмы для создания подземелий, карт высот и весовых таблиц лута на базе детерминированного сида.

Отрисовывает ли procedural-gen тайлы прямо в игре?

Нет, алгоритмы формируют данные в виде сеток или массивов без графики. Для раскраски тайлов в Godot или Unity потребуются отдельные специализированные инструменты.

Исходный текст

SKILL.md · Apache-2.0
---
name: procedural-gen
description: >
  Generate game content procedurally — seeded deterministic RNG, value/Perlin/
  Simplex noise for terrain and heightmaps, grid dungeon generation (rooms +
  corridors, BSP, random walk, wave function collapse), and weighted loot/drop
  tables. Engine-neutral algorithms. Use when the user mentions procedural
  generation, perlin/simplex noise, random seed, dungeon generator, WFC,
  heightmap/terrain, or loot tables.
---

# Procedural generation

Generate levels, terrain, and loot from compact rules and a seed. The throughline
of good procgen is **determinism**: a single seed reproduces the same world, so
bugs are repeatable and players can share seeds. This skill owns the core
algorithms — noise, seeded RNG, dungeon layout, weighted tables; genres like
`roguelike` and `survival-crafting` consume it.

## When to use

- Use to generate maps, dungeons, terrain heightmaps, item drops, or any content
  you do not want to author by hand.
- Use when results must be **reproducible from a seed** (debugging, daily
  challenges, shareable worlds).
- Use to pick weighted random outcomes (loot rarity, spawn tables).

**When *not* to use:** for the engine's tile API to *paint* the result, use
`godot-tilemap` or `unity-tilemap-2d`. For routing AI through the generated map,
use `game-ai`. For carefully hand-paced levels, use `level-design` — procgen and
authored design are complementary, not interchangeable.

## Core workflow

1. **Own your randomness.** Create one seeded RNG instance and pass it
   everywhere. Never call the global/static random in generation code — it makes
   results irreproducible and order-dependent.
2. **Pick the technique for the content.** Continuous terrain/heightmaps → noise.
   Discrete rooms/corridors → space partitioning or agent-based carving.
   Outcomes with rarities → weighted tables.
3. **Generate into a plain data grid/array first**, decoupled from rendering.
   Generation fills `int[][]` or a dict; a separate pass draws it.
4. **Validate before shipping the result to the player.** Is every room
   reachable? Is the spawn safe? Is there a path to the exit? Reject or repair
   layouts that fail; do not hand the player a broken map.
5. **Tune with the seed fixed** so each parameter change is visible in isolation,
   then sweep seeds to check the distribution, not just one lucky map.

## Patterns

### 1. Seeded, deterministic RNG (the foundation)

```python
import random
rng = random.Random(seed)        # a dedicated instance — NOT the global random.*
room_count = rng.randint(5, 12)  # same seed -> same sequence, every run
# RIGHT: thread `rng` through every function that makes a choice.
# WRONG: calling random.randint(...) (global state) — order-dependent, unseedable.
```

Engine equivalents: Godot 4.7 `var rng := RandomNumberGenerator.new(); rng.seed = s`
(save `rng.state` to resume a sequence mid-way); Unity 6.3
`new Unity.Mathematics.Random(seed)` (a `uint`, must be non-zero) or
`new System.Random(seed)`. Avoid `UnityEngine.Random.InitState` for generation:
it seeds the one global generator that every other script also draws from.
Store the seed in the save file so a world can be regenerated.

### 2. Fractal (fBm) noise for heightmaps

```python
# Sum several octaves: each higher octave has higher frequency, lower amplitude.
def fbm(noise, x, y, octaves=5, lacunarity=2.0, gain=0.5):
    total, amp, freq, norm = 0.0, 1.0, 1.0, 0.0
    for _ in range(octaves):
        total += amp * noise(x * freq, y * freq)   # noise() returns ~0..1
        norm  += amp                                # track total amplitude
        amp   *= gain                               # each octave contributes less
        freq  *= lacunarity                         # ...at a higher frequency
    return total / norm                             # normalize back into 0..1

# Redistribute to carve flat valleys / sharpen peaks: higher exp -> more lowland.
elevation = pow(fbm(noise, nx, ny), 2.2)
```

Use a real noise library (`FastNoiseLite`, `opensimplex`,
`Unity.Mathematics.noise`, or `Mathf.PerlinNoise`) — do not implement gradient
noise yourself. Seed **elevation and moisture with different seeds** so a
biome lookup over both fields isn't perfectly correlated. Full biome lookup and
island shaping are in `references/noise.md`.

### 3. Weighted loot table (rarity-correct selection)

```python
# Roll proportional to weight: common drops far more often than legendary.
def weighted_pick(rng, table):           # table: list of (item, weight)
    total = sum(w for _, w in table)
    roll = rng.uniform(0, total)          # a point on the cumulative line
    upto = 0.0
    for item, w in table:
        upto += w
        if roll < upto:                   # first bucket the roll falls into
            return item
    return next(i for i, w in reversed(table) if w > 0)  # roll == total (float edge)

loot = weighted_pick(rng, [("common", 70), ("rare", 25), ("legendary", 5)])
```

Weights need not sum to 100 — they are relative, and a weight of 0 never drops.
Built-ins do the same job: Python `rng.choices(items, weights)`, Godot
`rng.rand_weighted(PackedFloat32Array(weights))` (returns an index). To prevent
bad streaks, use a "pity"/bag system (see `references/dungeon-generation.md`
notes on distributions).

### 4. Rooms-and-corridors dungeon (sketch)

```python
# 1. Place non-overlapping rooms; 2. connect them; 3. carve into the grid.
rooms = []
for _ in range(attempts):
    r = Rect(rng.randint(1, W-w-1), rng.randint(1, H-h-1), w, h)
    if not any(r.intersects(o.expand(1)) for o in rooms):  # keep a 1-tile gap
        rooms.append(r)
for a, b in zip(rooms, rooms[1:]):       # connect each room to the next
    carve_l_corridor(grid, a.center, b.center, rng)   # horizontal then vertical
```

The complete generator (BSP partitioning, L-corridors, reachability check, and
random-walk caves) is in `references/dungeon-generation.md`.

## Pitfalls

- **Using the global RNG** inside generation makes worlds unreproducible and
  breaks the moment call order changes. Always pass a seeded instance.
- **Correlated noise fields**: sampling elevation and moisture from the *same*
  seed/offset produces biomes that line up in bands. Offset or reseed each field.
- **Octave artifacts**: adding octaves without renormalizing pushes values out of
  `0..1`; divide by the summed amplitude (and beware library output ranges — some
  return `-1..1`, some `0..1`).
- **No connectivity check**: rooms or caves can end up isolated. Flood-fill from
  the spawn and discard/reconnect unreachable regions before play.
- **Unbounded placement loops**: "keep trying until N rooms fit" can spin forever
  on a small grid. Cap attempts and accept fewer rooms.
- **Seeding once globally, then relying on frame timing**: any non-deterministic
  input (time, physics, hash randomization) leaking into generation destroys
  reproducibility. A common hidden one: `rng.choice(list(some_set))` over
  strings in Python, whose set order changes per process. Sort first.
- **Seeds that stop matching after an update.** Library RNGs promise the same
  sequence only on the same version: Python guarantees only `random()` across
  versions (not `randint`/`choice`), .NET says `System.Random` may change
  between major versions, and Godot calls its PCG32 an implementation detail.
  If shared seeds, daily challenges or seed-only saves must survive updates,
  ship your own small PRNG (PCG32, xorshift, SplitMix64) with a test that pins
  its first outputs — or save the generated result instead of the seed.
- **Flat noise at integer coordinates**: Perlin noise is 0 at every integer
  lattice point, so sampling raw `noise(x, y)` (e.g. `Mathf.PerlinNoise`) at
  whole tile coordinates returns the same value everywhere. Scale by a
  non-integer frequency (`x / width * f`); libraries with a frequency setting,
  such as FastNoiseLite, apply it for you.

## References

- `references/noise.md` — octaves/lacunarity/gain, redistribution, island
  shaping, two-axis biome lookup, blue-noise object scatter.
- `references/dungeon-generation.md` — BSP, rooms+corridors, random-walk caves,
  cellular-automata smoothing, wave function collapse, connectivity validation,
  distribution/pity tables.

## Related skills

- `godot-tilemap`, `unity-tilemap-2d` — paint the generated grid into the engine.
- `game-ai` — pathfinding over the generated graph.
- `level-design` — pacing and hand-authored structure that procgen complements.
- `roguelike`, `survival-crafting` — genres that compose this skill.

© gamedev-skills · Apache-2.0 · gamedev-skills/awesome-gamedev-agent-skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой