TExcelTAD
Home › Algebra › Systems of Equations for Game Balancing

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 3×33 \times 3 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 ww, ss and ii, each row is a linear equation:

3w+2s+i=17w+4s+2i=242w+s+3i=22\begin{aligned} 3w + 2s + i &= 17 \\ w + 4s + 2i &= 24 \\ 2w + s + 3i &= 22 \end{aligned}

Any method from the systems chapter solves it: elimination, the matrix method or Cramer's rule. By elimination:

(1)−3⋅(2):3w+2s+i−3w−12s−6i=17−72  ⟹  −10s−5i=−55  ⟹  2s+i=11(3)−2⋅(2):2w+s+3i−2w−8s−4i=22−48  ⟹  −7s−i=−26  ⟹  7s+i=26subtract:5s=15  ⟹  s=3, i=11−6=5back into (2):w+12+10=24  ⟹  w=2\begin{aligned} (1) - 3 \cdot (2)\text{:} &\quad 3w + 2s + i - 3w - 12s - 6i = 17 - 72 \;\Longrightarrow\; -10s - 5i = -55 \;\Longrightarrow\; 2s + i = 11 \\ (3) - 2 \cdot (2)\text{:} &\quad 2w + s + 3i - 2w - 8s - 4i = 22 - 48 \;\Longrightarrow\; -7s - i = -26 \;\Longrightarrow\; 7s + i = 26 \\ \text{subtract:} &\quad 5s = 15 \;\Longrightarrow\; s = 3,\ i = 11 - 6 = 5 \\ \text{back into (2):} &\quad w + 12 + 10 = 24 \;\Longrightarrow\; w = 2 \end{aligned}

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.

python · try it yourself
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:

  1. Recipes and sell prices: value of inputs=value of output\text{value of inputs} = \text{value of output}. If a sword made from 2 iron and 1 wood (value 12) sells for 13, players can farm 1 gold per craft forever.
  2. Exchange cycles: for a market that trades a→b→c→aa \to b \to c \to a, the product of the exchange rates around the cycle must be 1. A product above 1 is a money printer.
python · try it yourself
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 6/56/5 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 Starter+Builder\text{Starter} + \text{Builder}), 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:

python · try it yourself
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 ii): 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 A=2 gems+3 coins\text{A} = 2\ \text{gems} + 3\ \text{coins} costs 19 gold; bundle B=1 gem+4 coins\text{B} = 1\ \text{gem} + 4\ \text{coins} costs 17. Find the value of a gem and a coin.

Answer

Gem=5 gold\text{Gem} = 5\ \text{gold}, coin=3 gold\text{coin} = 3\ \text{gold}.

Solution
2g+3c=19g+4c=17  ⟹  g=17−4c2(17−4c)+3c=19  ⟹  34−5c=19  ⟹  c=3, g=5\begin{aligned} 2g + 3c &= 19 \\ g + 4c &= 17 \;\Longrightarrow\; g = 17 - 4c \\ 2(17 - 4c) + 3c &= 19 \;\Longrightarrow\; 34 - 5c = 19 \;\Longrightarrow\; c = 3,\ g = 5 \end{aligned}

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
2a+b+c=39a+3b=272b+3c=57\begin{aligned} 2a + b + c &= 39 \\ a + 3b &= 27 \\ 2b + 3c &= 57 \end{aligned}
python · try it yourself
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: 18+6+15=3918 + 6 + 15 = 39, 9+18=279 + 18 = 27, 12+45=5712 + 45 = 57. ✓

Exercise 3: Find the leak

With wood=2\text{wood} = 2, stone=3\text{stone} = 3 and iron=5\text{iron} = 5, 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
2⋅2+4⋅3+1⋅5=4+12+5=212 \cdot 2 + 4 \cdot 3 + 1 \cdot 5 = 4 + 12 + 5 = 21

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 9/89/8, a 12.5% profit per loop.

Solution

Multiply the received/given ratios around the cycle:

14⋅32⋅31=98=1.125\frac{1}{4} \cdot \frac{3}{2} \cdot \frac{3}{1} = \frac{9}{8} = 1.125

Start with 8 fish: 2 cloth, then 3 salt, then 9 fish. To close it, change one rate, for example 1 salt → 8/38/3 fish (or 3 salt → 8 fish).

Test yourself

The coefficient matrix of a 3×33 \times 3 pricing system has determinant 0. What follows?

  1. The prices are all zero
  2. There is exactly one solution
  3. There is no unique solution: either none or infinitely many
  4. The system is solved by Cramer's rule

Exchange rates around a loop multiply to 1.2. What does that mean?

  1. Each trip around the loop gives 20% more than you started with
  2. The economy is closed
  3. Players lose 20% per trip
  4. Nothing, rates are independent

Why use Fraction instead of floats for in-game prices?

  1. Fractions are faster
  2. So results like 2 and 3 come out exactly, with no 2.9999999 to round or show
  3. Floats cannot store integers
  4. NumPy requires it