Sub topic 4
Experience Points and Levels
This chapter covers experience points (XP) and levels: what each one is, how they relate, and how to implement them without bugs. It assumes you can read short Python samples and are comfortable with exponents and sums. It also assumes you know the three progression axes (power, content, skill) from earlier in the tutorial. XP and levels are the most common way to drive the power axis, and they often feed the other two.
What XP and levels are
Experience points are a number the game increases when the player does something it wants to encourage. A level is a label for a range of that number. The player sees "Level 7", but the game stores a running XP total, and the level is derived from it.
This split has three consequences.
- XP is the currency of effort. Designers decide which actions pay XP: defeating enemies, finishing quests, discovering places, crafting. Whatever pays XP is what players will do more of.
- Levels are the milestones. Crossing a threshold is a discrete event you can attach rewards to: stat increases, new abilities, new areas.
- Thresholds are the tuning knob. Changing the XP required for each level changes the pace of the whole game without touching any content.
Why store XP and derive the level
Many first implementations store both xp and level and update them together. This works until something changes the curve. If you rebalance the thresholds in a patch, saved level values no longer match saved xp values, and you have to write a migration.
If you store only the total XP, a curve change is just a new function. Every save file stays valid, and every player's level is recomputed from the new curve. The cost is a small computation each time you need the level. You can cache the result in memory.
Some games deliberately store the level instead, so that players are never demoted by a patch. If you choose that, record the curve version as well. Either choice is fine, but you should make it on purpose.
A per-level cost curve
The simplest model gives each level an XP cost. Let xp_to_next(L) be the XP needed to go from level L to L + 1. The common exponential form is:
cost(L) = base × growth^(L − 1)
Each level costs a fixed percentage more than the previous one. With growth = 1.15, each level costs 15% more.
def xp_to_next(level, base=100, growth=1.15):
"""XP needed to go from `level` to `level + 1`."""
return round(base * growth ** (level - 1))
def total_xp(level, base=100, growth=1.15):
"""Cumulative XP needed to reach `level` from level 1."""
return sum(xp_to_next(l, base, growth) for l in range(1, level))
def level_from_xp(xp, base=100, growth=1.15):
level = 1
while xp >= xp_to_next(level, base, growth):
xp -= xp_to_next(level, base, growth)
level += 1
return level
print(xp_to_next(1), xp_to_next(10), total_xp(10), level_from_xp(500))This prints 100 352 1678 5. Going from level 1 to 2 costs 100 XP. Going from level 10 to 11 costs 352 XP. Reaching level 10 from the start takes 1,678 XP in total. A player with 500 XP is level 5, because the first four levels cost 100 + 115 + 132 + 152 = 499 XP, leaving 1 XP of progress.
Three details in this code matter.
total_xp(level)sums the costs of levels1throughlevel - 1. Level 1 needs 0 XP, which is the empty sum.level_from_xpsubtracts each cost as it passes, so it handles awards that skip several levels at once.roundis applied to each level's cost, not to the final sum. Because the cost is rounded per level, the cumulative total is exactly the sum of what the player sees, with no hidden fractions.
Curve shapes and their effect
The growth value sets how fast costs climb. Small changes compound strongly. This table shows XP to next level with base = 100.
| Level | growth 1.10 | growth 1.15 |
|---|---|---|
| 10 | 236 | 352 |
| 20 | 612 | 1,423 |
| 30 | 1,586 | 5,758 |
At 1.15, level 30 costs about 58 times what level 1 costs. At 1.10, it costs about 16 times. A player earning a steady 100 XP per hour feels the first curve become a wall long before the second does.
Other shapes are common:
- Linear:
cost = base × L. Each level takes noticeably longer than the last, but only gently. Good for short games. - Polynomial:
cost = base × L^k, withkaround 1.5 to 3. It grows more slowly than an exponential at high levels, so late game stays reachable. - Table-driven: a hand-written list of costs. Designers can shape the curve exactly, such as a fast first hour and a plateau in the middle. The next chapter covers designing the curve in more detail.
Matching the curve to the earning rate
A level curve is only half the pacing system. The other half is how much XP the player earns per unit of time, and that rate usually changes as the game goes on. Time to level is cost(L) / earn_rate(L).
If costs grow 15% per level and enemies grow 15% in XP value per level, time per level stays constant. This is a common target when you want every level to feel equally paced. If enemies grow more slowly than costs, levels get slower, which is a typical design for the late game. If enemies grow faster, levels speed up, and players can outrun your content.
One practical technique is to define the XP value of an enemy as a function of the level difference between player and enemy. A common pattern gives full XP at equal level, reduced XP when the enemy is much lower, and a modest bonus when it is higher. This prevents farming trivial enemies for fast levels, and it keeps the earning rate tied to the content the player should be doing.
Implementing thresholds efficiently
level_from_xp above loops from level 1 each call. For a 100-level game that is cheap, but you may call it every frame for UI. A better approach precomputes cumulative thresholds once and searches them.
from bisect import bisect_right
from itertools import accumulate
MAX_LEVEL = 20
def xp_to_next(level, base=100, growth=1.15):
return round(base * growth ** (level - 1))
# THRESHOLDS[i] is the total XP needed to reach level i + 1.
THRESHOLDS = [0] + list(accumulate(xp_to_next(l) for l in range(1, MAX_LEVEL)))
def level_from_total(xp):
return bisect_right(THRESHOLDS, xp)
def add_xp(total, gained):
"""Return the new XP total and the number of levels gained."""
before = level_from_total(total)
total += gained
return total, level_from_total(total) - before
print(add_xp(1600, 200), level_from_total(10**9))This prints (1800, 1) 20. The player moves from level 9 (1,600 XP) to level 10 (1,800 XP), so one level is gained. An enormous XP total still returns level 20, because the table has only 20 entries.
The table does two jobs. bisect_right finds the level in logarithmic time. The table length also enforces the level cap, since the result can never exceed MAX_LEVEL.
Edge cases to handle
- Multiple level-ups from one award. A quest reward can grant enough XP to skip levels. Compute levels gained as a difference, then grant the rewards for every level crossed, not only the last one. Missing this is a common bug that silently drops skill points.
- The level cap. Decide what XP does at the cap. Options are to stop accumulating, to keep accumulating toward a secondary system such as prestige or paragon levels, or to convert it into currency. Whichever you pick, do not let the total overflow into a level that has no data.
- Rounding drift. Rounding the cumulative total instead of each cost can make the displayed XP-to-next differ from the real one by 1. Round once, per level, and derive everything else from those integers.
- Large numbers. Exponential curves can produce huge totals. Use a data type that will not overflow. Python integers are unbounded, but a save format or a game engine's 32-bit integer is not. At
growth = 1.15, a 100-level curve reaches costs in the hundreds of millions. - Negative XP. Death penalties that remove XP can push a player below the start of their level. Decide whether levels can be lost. Many games clamp XP loss at the current level's threshold so players are never demoted.
- Curve changes after launch. If you change
growthorbase, derived levels shift for everyone. Version the curve and announce it as a balance change.
Choosing parameters
Start from the goal, not from the formula. Decide how long the player should take to reach the cap, and decide the earning rate at the start. Then pick base so the early levels arrive quickly, since early level-ups teach the player that the system exists. Pick growth so the cumulative total at the cap matches your target playtime. Because total_xp is a geometric sum, you can solve for it: total ≈ base × (growth^(n−1) − 1) / (growth − 1) for n levels. Check your result against the code rather than trusting the algebra alone, since per-level rounding shifts the total slightly.
Exercise
Using the exponential curve with base=100 and growth=1.15, a player has exactly 1,678 XP. A boss then awards 700 XP. How many levels does the player gain? Use the cumulative values from this chapter: level 10 needs 1,678 XP, and the cost to go from level 10 to 11 is 352 XP. The cost from level 11 to 12 is round(100 × 1.15^10), which is 405.
Show answer
The player starts at level 10, since 1,678 XP is exactly the level 10 threshold. The new total is 2,378 XP. Level 11 needs 1,678 + 352 = 2,030 XP, so the player reaches it. Level 12 needs 2,030 + 405 = 2,435 XP, and 2,378 is below that. The player gains exactly one level and ends at level 11 with 348 XP of progress (2,378 − 2,030). The remaining 57 XP are needed for level 12.
Exercise
Why is it usually safer to save the XP total than to save the level number?
Show answer
The level can always be recomputed from the XP total using the current curve, so a rebalance of the thresholds never leaves a save file inconsistent. If both values are stored, a curve change makes them disagree and requires a migration.