Systems of Equations for Game Balancing
Game designers often know what whole bundles, recipes or fights should be worth, and need the value of each piece. "Three bundles with known prices, three unknown resource values" is a linear system. This lesson solves one exactly, then uses the answer to check that the game's economy closes: that no chain of trades or crafts creates gold out of nothing.
From design notes to equations
A designer writes down three shop bundles and the prices they want:
| Bundle | Wood | Stone | Iron | Price (gold) |
|---|---|---|---|---|
| Starter | 3 | 2 | 1 | 17 |
| Builder | 1 | 4 | 2 | 24 |
| Smith | 2 | 1 | 3 | 22 |
With unknown unit values , and , each row is a linear equation:
Any method from the systems chapter solves it: elimination, the matrix method or Cramer's rule. By elimination:
So wood is worth 2 gold, stone 3, iron 5.
Solving it in code
Use Fraction when the values must be exact (prices you will print in the UI), and NumPy when speed matters and floats are fine. A unique solution exists exactly when the coefficient matrix has a non-zero determinant.
from fractions import Fraction
import numpy as np
import sympy as sp
A = [[3, 2, 1], [1, 4, 2], [2, 1, 3]]
b = [17, 24, 22]
def solve_exact(A, b):
n = len(A)
M = [[Fraction(v) for v in row] + [Fraction(rhs)] for row, rhs in zip(A, b)]
for col in range(n):
pivot = next(r for r in range(col, n) if M[r][col] != 0)
M[col], M[pivot] = M[pivot], M[col]
for r in range(n):
if r != col and M[r][col] != 0:
f = M[r][col] / M[col][col]
M[r] = [x - f * y for x, y in zip(M[r], M[col])]
return [M[r][n] / M[r][r] for r in range(n)]
print("exact :", [str(v) for v in solve_exact(A, b)])
print("numpy :", [round(float(v), 10) for v in np.linalg.solve(A, b)])
print("det :", sp.Matrix(A).det())exact : ['2', '3', '5']
numpy : [2.0, 3.0, 5.0]
det : 25
The next(…) line picks a row with a non-zero pivot; if none exists the matrix is singular and the call fails (see the last section).
Does the economy close?
Values only matter if the rest of the game respects them. A loop is closed when converting resources around it returns exactly what you started with. Two checks:
- Recipes and sell prices: . If a sword made from 2 iron and 1 wood (value 12) sells for 13, players can farm 1 gold per craft forever.
- Exchange cycles: for a market that trades , the product of the exchange rates around the cycle must be 1. A product above 1 is a money printer.
from fractions import Fraction as F
value = {"wood": F(2), "stone": F(3), "iron": F(5)}
recipes = {"plank wall": ({"wood": 4, "stone": 1}, 11),
"sword": ({"iron": 2, "wood": 1}, 13),
"forge": ({"stone": 3, "iron": 2}, 19)}
for name, (inputs, sell) in recipes.items():
cost = sum(value[r] * k for r, k in inputs.items())
status = "closed" if cost == sell else f"leak {sell - cost:+} per craft"
print(f"{name:10}: inputs {cost}, sells {sell} -> {status}")
def cycle_gain(trades):
gain = F(1)
for give, get in trades: # (amount given, amount received)
gain *= F(get, give)
return gain
print("rates 3w->2s, 5s->3i, 2i->5w :", cycle_gain([(3, 2), (5, 3), (2, 5)]))
print("rates 3w->2s, 5s->3i, 1i->3w :", cycle_gain([(3, 2), (5, 3), (1, 3)]))plank wall: inputs 11, sells 11 -> closed
sword : inputs 12, sells 13 -> leak +1 per craft
forge : inputs 19, sells 19 -> closed
rates 3w->2s, 5s->3i, 2i->5w : 1
rates 3w->2s, 5s->3i, 1i->3w : 6/5
The first market is fair: going around the loop multiplies your wood by exactly 1. In the second, iron → wood at 1:3 is too generous, and every trip around the loop gives of the wood you started with, a 20% gain per loop.
Tip: Run these checks in a unit test over the game's data files. Balancing changes are frequent, and a single edited recipe can open a loop that players find within hours.
When the system has no unique answer
If the designer's constraints depend on each other (for example a fourth bundle that is just ), they add no information. With only dependent rows, the determinant is 0 and there are either no solutions (contradictory prices) or infinitely many (under-specified values). SymPy's linsolve shows which:
import sympy as sp
w, s, i = sp.symbols("w s i")
A = sp.Matrix([[3, 2, 1], [1, 4, 2], [4, 6, 3]]) # row 3 = row 1 + row 2
print("det:", A.det())
print("consistent:", sp.linsolve((A, sp.Matrix([17, 24, 41])), w, s, i))
print("contradictory:", sp.linsolve((A, sp.Matrix([17, 24, 40])), w, s, i))det: 0
consistent: {(2, 11/2 - i/2, i)}
contradictory: EmptySet
The consistent case still pins wood at 2 but leaves one value free (stone is written in terms of ): the designer has to fix one more price. The contradictory case is the empty set: the bundle prices cannot all be honoured. The same row reduction is studied in depth in Gaussian elimination.
In software
- Shops and crafting: derive unit values from target bundle prices, then test every recipe against them.
- Combat tuning: solve for per-hit damage values from target "hits to kill" numbers.
- Data pipelines: "these three totals are known, find the parts" appears in accounting and in tomography alike; large versions use NumPy or sparse solvers.
Exercises
Exercise 1: Two resources
Bundle costs 19 gold; bundle costs 17. Find the value of a gem and a coin.
Answer
, .
Solution
Exercise 2: Damage values (code)
Three combos are tested on a training dummy. Combo 1 uses 2 slashes, 1 kick, 1 fireball and deals 39 damage; combo 2 uses 1 slash, 3 kicks, 0 fireballs and deals 27; combo 3 uses 0 slashes, 2 kicks, 3 fireballs and deals 57. Find each move's damage with np.linalg.solve.
Answer
Slash 9, kick 6, fireball 15.
Solution
import numpy as np
A = [[2, 1, 1], [1, 3, 0], [0, 2, 3]]
print([round(float(v), 9) for v in np.linalg.solve(A, [39, 27, 57])])[9.0, 6.0, 15.0]
Check: , , . ✓
Exercise 3: Find the leak
With , and , a "tower" recipe uses 2 wood, 4 stone and 1 iron and sells for 20. Is the recipe closed? If not, what sell price closes it?
Answer
No: the inputs are worth 21, so the recipe loses 1 gold per craft. A price of 21 closes it.
Solution
Selling at 20 is not an exploit (players lose gold), but nobody will craft it. Set the price to 21 or change the recipe.
Exercise 4: Exchange cycle
A market trades 4 fish → 1 cloth, 2 cloth → 3 salt, 1 salt → 3 fish. Does it close? What is the gain per trip?
Answer
No: the gain is , a 12.5% profit per loop.
Solution
Multiply the received/given ratios around the cycle:
Start with 8 fish: 2 cloth, then 3 salt, then 9 fish. To close it, change one rate, for example 1 salt → fish (or 3 salt → 8 fish).
Test yourself
The coefficient matrix of a pricing system has determinant 0. What follows?
- The prices are all zero
- There is exactly one solution
- There is no unique solution: either none or infinitely many
- The system is solved by Cramer's rule
Exchange rates around a loop multiply to 1.2. What does that mean?
- Each trip around the loop gives 20% more than you started with
- The economy is closed
- Players lose 20% per trip
- Nothing, rates are independent
Why use Fraction instead of floats for in-game prices?
- Fractions are faster
- So results like 2 and 3 come out exactly, with no 2.9999999 to round or show
- Floats cannot store integers
- NumPy requires it