Sub topic 13
Implementing Progression as Data
This chapter assumes you have read the earlier chapters on XP curves, unlock conditions, and skill trees. You should be able to read short Python programs and know what a dictionary, a list, and a recursive function are. Everything here applies to any language, and Python is used for the samples.
Why Progression Belongs in Data
Progression rules change more often than almost any other part of a game. A designer who wants level 5 to unlock the caves at level 6 should not need to edit engine code, recompile, and ask a programmer to review the change. If the rule is a row in a data file, the change takes seconds. It also shows up cleanly in version control as a one-line diff.
The pattern is simple:
- Data states what is true: costs, levels, prerequisites.
- Code states how to evaluate it: "can this player learn this skill?"
- A validator checks that the data makes sense before the game ever runs.
The earlier chapters already used this split. The UNLOCKS dictionary holds the rules, and is_unlocked is the only code that interprets them. The SKILLS dictionary holds costs and prerequisites, and can_learn and respec interpret them. The same split applies to the level curve, which needs only three numbers: base, growth, and a maximum level.
What Goes in Data and What Stays in Code
Not everything should become data. A rule that is just a number or a list of names belongs in data. A rule with real logic belongs in code.
| Belongs in data | Stays in code |
|---|---|
| XP curve parameters (`base`, `growth`, `max_level`) | The formula that turns parameters into XP |
| Unlock level, prerequisite names, required items | The check that combines those conditions |
| Skill cost and prerequisite list | The rule "all prerequisites must be learned" |
| Skill points granted per level | Awarding points when the player levels up |
| Names shown to the player (or keys to a text table) | Rendering and UI layout |
If you find yourself inventing a mini-language inside the data, such as strings like "level > 5 and not has_item('torch')", stop. You are building a scripting engine, which is harder to validate than a handful of fixed fields. Add a new field when a new kind of condition appears.
A Single Config File
Keep all three systems in one document so the validator can check references across them. For example, an unlock may require an item, and that item must exist. JSON is a good default because every language reads it and it forbids comments and trailing commas, which keeps files uniform. YAML or TOML are fine if your team prefers them. Spreadsheets exported to CSV suit flat tables such as per-level rewards, but they are awkward for prerequisite lists.
Note that JSON has no set type. Lists in the file become sets or other structures at load time, if your code needs them.
import copy
import json
RAW = """
{
"curve": {"base": 100, "growth": 1.15, "max_level": 20, "skill_points_per_level": 1},
"items": ["silver_key"],
"unlocks": {
"forest": {"level": 1},
"caves": {"level": 5, "requires": ["forest"]},
"boss_gate": {"level": 10, "requires": ["caves"], "items": ["silver_key"]}
},
"skills": {
"slash": {"cost": 1, "requires": []},
"whirlwind": {"cost": 2, "requires": ["slash"]},
"berserk": {"cost": 2, "requires": ["slash"]},
"execute": {"cost": 3, "requires": ["whirlwind", "berserk"]}
}
}
"""
def find_cycle(graph):
"""Return a list of names forming a cycle, or None.
graph maps each name to the list of names it depends on.
"""
white, grey, black = 0, 1, 2
color = {name: white for name in graph}
stack = []
def visit(name):
color[name] = grey
stack.append(name)
for dep in graph[name]:
if dep not in graph:
continue # unknown names are reported separately
if color[dep] == grey:
return stack[stack.index(dep):] + [dep]
if color[dep] == white:
found = visit(dep)
if found:
return found
stack.pop()
color[name] = black
return None
for name in graph:
if color[name] == white:
found = visit(name)
if found:
return found
return None
def validate(cfg):
"""Return a list of human-readable problems. An empty list means valid."""
errors = []
curve = cfg["curve"]
if curve["growth"] < 1:
errors.append("curve.growth must be at least 1")
if curve["max_level"] < 1:
errors.append("curve.max_level must be at least 1")
items = set(cfg.get("items", []))
unlocks = cfg["unlocks"]
for name, rule in unlocks.items():
for req in rule.get("requires", []):
if req not in unlocks:
errors.append(f"unlock {name!r}: unknown prerequisite {req!r}")
for item in rule.get("items", []):
if item not in items:
errors.append(f"unlock {name!r}: unknown item {item!r}")
if rule.get("level", 1) > curve["max_level"]:
errors.append(f"unlock {name!r}: level is above max_level")
skills = cfg["skills"]
for name, node in skills.items():
if node["cost"] < 1:
errors.append(f"skill {name!r}: cost must be at least 1")
for req in node["requires"]:
if req not in skills:
errors.append(f"skill {name!r}: unknown prerequisite {req!r}")
graphs = (
("unlock", {n: r.get("requires", []) for n, r in unlocks.items()}),
("skill", {n: s["requires"] for n, s in skills.items()}),
)
for label, graph in graphs:
cycle = find_cycle(graph)
if cycle:
errors.append(f"{label} cycle: " + " -> ".join(cycle))
return errors
cfg = json.loads(RAW)
print(validate(cfg))
broken = copy.deepcopy(cfg)
broken["unlocks"]["caves"]["requires"] = ["cave"] # typo
broken["skills"]["slash"]["requires"] = ["execute"] # circular
for problem in validate(broken):
print(problem)The first call prints []. The broken copy prints two lines: an unknown prerequisite 'cave' for caves, and a skill cycle slash -> execute -> whirlwind -> slash.
What the Validator Catches
Each check targets a failure that would otherwise appear only when a player hits it.
- Dangling references. A typo in a prerequisite name makes
is_unlockedraise aKeyErroror, worse, silently never unlock. Checking that every name exists turns this into a build-time error. - Cycles. If A requires B and B requires A, neither can ever be obtained. This is a soft lock: the player is stuck with no error message. The depth-first search above colors each node as unvisited, in progress, or finished. Reaching an in-progress node means a cycle.
- Unreachable content. An unlock at level 25 in a game that ends at level 20 can never open. The
max_levelcomparison catches it. - Nonsense numbers. A growth factor below 1 makes levels cheaper over time. A skill cost of 0 or less lets players gain points by learning skills.
Run the validator in your automated tests and when the game loads data. A designer edit that breaks a rule then fails the build instead of reaching players.
Generating Review Tables From the Same Data
Designers reason about pacing in tables: how much XP each level costs, and the running total. Generate that table from the config instead of maintaining a copy by hand. A hand-maintained copy goes stale the first time someone changes growth.
def level_table(curve):
"""Rows of (level, xp_to_next, cumulative_xp_at_level_start)."""
rows = []
total = 0
for level in range(1, curve["max_level"]):
need = round(curve["base"] * curve["growth"] ** (level - 1))
rows.append((level, need, total))
total += need
return rows
curve = {"base": 100, "growth": 1.15, "max_level": 6}
for level, need, total in level_table(curve):
print(f"level {level}: needs {need:>4} XP, starts at {total:>4} XP")This prints five rows, from level 1 needing 100 XP to level 5 needing 175 XP. Because the table and the game read the same curve, they cannot disagree. The same table can feed a spreadsheet or the telemetry comparisons from the next chapter.
Common Errors
- Two sources of truth. The UI shows "Requires level 5" typed into a text file while the data says 6. Have the UI read the data, or reference rules by key so text is generated from them.
- Using display names as keys. If
"Whirlwind"is both the key and the label, renaming it for polish breaks save files. Use a stable id such aswhirlwindand keep display text elsewhere. - Removing entries that saves refer to. A player's save may list a skill you deleted. Decide on the migration, such as refunding the cost, before shipping the deletion.
- Floating-point drift.
growth ** (level - 1)is computed with floats and then rounded. Results are stable on the same platform, but if the server and client must agree exactly, test across both or store the computed table as integers. - Validating only the happy path. A file can pass every check above and still be bad design. For example, if the points available by
max_levelexceed the total cost of every skill, players can buy the whole tree and the choices from the earlier chapters disappear.
Exercise
Exercise
The validator above does not check that players can afford the whole tree or that every skill can eventually be learned. Describe one extra check that compares the skill tree to the curve, and say which fields it reads and what result should be reported.
Show answer
Add a budget check. Compute the points players can earn: (maxlevel - 1) * skillpointsperlevel from the curve section. Compute the total cost: the sum of every skill's "cost" in the skills section. If total cost is less than or equal to the budget, report that the whole tree can be bought, so builds do not diverge and choices are not meaningful. If a single skill's cost, plus the costs of all its prerequisites, is greater than the budget, report that the skill is unreachable. Both checks use only the data, so they can run in the same validate function.