When Should You Build the Farm?
In strategy games and in real capacity planning, the same dilemma keeps showing up. A production facility pays off only after a delay, and the resources spent building it are taken from the very thing you want to grow. A farm that starts producing food three turns after construction begins is a clean example. Build too early and the construction cost starves the young population. Build too late and the population outgrows its food supply.
In this article we turn that dilemma into a concrete optimization problem, solve it exactly in Python, and visualize why the optimum looks the way it does.
1. Problem Setting
We plan over $T = 20$ turns. A village starts with $P_0 = 50$ people and an initial food stock $S_0 = 80$. At most $K = 5$ farms can be built, and each farm has three properties.
- It costs $C = 90$ food units in total, paid in equal installments over the three turns of construction.
- It starts producing $F = 16$ food per turn exactly $3$ turns after construction begins.
- Construction may start at any turn $b_k \in {1, \dots, 20}$, or never (we encode “never” as $b_k = 21$).
A build plan is therefore the vector $\mathbf{b} = (b_1, \dots, b_K)$.
State transition
The number of farms producing at turn $t$ and the number under construction are
$$
A_t(\mathbf{b}) = \sum_{k=1}^{K} \mathbb{1}\left[b_k + 3 \le t\right], \qquad
B_t(\mathbf{b}) = \sum_{k=1}^{K} \mathbb{1}\left[b_k \le t < b_k + 3\right].
$$
Food available in turn $t$, after paying construction installments, is
$$
V_t = S_{t-1} + \left(M + F,A_t\right) - \frac{C}{3},B_t ,
$$
where $M = 40$ is the output of the existing fields. The demand is $D_t = c,P_{t-1}$ with $c = 0.8$ food per person. The satisfaction ratio is $\rho_t = \max\left(V_t / D_t,\ 0\right)$.
Population grows when food is plentiful and shrinks under shortage:
$$
P_t = P_{t-1}\left[1 + r,\mathrm{clip}!\left(\frac{\rho_t - 1}{0.3},,0,,1\right)\left(1 - \frac{P_{t-1}}{N_{\max}}\right) - \delta,\mathrm{clip}\left(1-\rho_t,,0,,1\right)\right]
$$
with $r = 0.14$, $\delta = 0.5$ and $N_{\max} = 600$. Leftover food is stored with $10%$ spoilage:
$$
S_t = 0.9,\max\left(V_t - D_t,\ 0\right).
$$
Objective
$$
\max_{\mathbf{b}\in{1,\dots,21}^K} ; P_{20}(\mathbf{b})
$$
Because farms are interchangeable, only the multiset of build turns matters. The number of distinct plans is
$$
\binom{21 + 5 - 1}{5} = 53{,}130 ,
$$
which is small enough to enumerate exhaustively and obtain a provably optimal plan.
2. Source Code
The simulator is vectorized over all plans at once. Instead of calling a Python loop 53,130 times, it runs a single 20-step loop on arrays of length 53,130. This is what makes the full search finish in a fraction of a second.
1 | import itertools |
3. Code Walkthrough
Parameters. All model constants live at the top, so you can change the cost, the delay or the farm output and immediately see how the optimal schedule shifts. NEVER = T + 1 is a sentinel meaning “this farm is never built”. With it, plans with fewer than five farms are represented in the same fixed-length array.
The simulator. simulate accepts an array of plans of shape $(n, K)$ and advances all of them through the 20 turns simultaneously.
activecounts farms whose production has started, which is the condition $b_k + 3 \le t$.buildingcounts farms in their three construction turns, which is the condition $b_k \le t < b_k + 3$. Each pays one third of the cost per turn.availis the stock plus production minus the construction installment. This is where the cost of building early enters the model.ratiois the satisfaction ratio $\rho_t$. Growth switches on smoothly once food exceeds $100%$ of demand and saturates at $130%$. Deaths grow linearly as the ratio falls below $100%$.Scarries leftover food forward with $10%$ spoilage. Spoilage matters because it stops the model from solving the problem by simply hoarding a huge stockpile early.
Exhaustive search. itertools.combinations_with_replacement generates every multiset of five build turns drawn from ${1,\dots,21}$, giving exactly $53{,}130$ rows. A single call to simulate evaluates all of them, so the optimum is guaranteed, not heuristic.
Tie-breaking. If several plans reach the same final population, the code picks the one with the fewest farms. A farm that adds nothing but still costs resources should not appear in the answer.
Best plan per farm count. The loop over k finds the best schedule for exactly $k$ farms. This isolates the marginal value of each additional farm.
Reference strategies. Four intuitive strategies, namely building everything immediately, building at an even pace, building everything late and building nothing, are simulated with record=True to keep their full histories for plotting.
Surface data. The last three build turns are frozen at their optimal values, while the first two sweep a $20 \times 20$ grid. This produces a smooth landscape in which the effect of timing is easy to see.
4. Visualization of the Results

How to read the six panels
Panel 1, the 3D surface. The two horizontal axes are the build turns of the first and second farms, and the height is the final population. The surface rises steeply when both farms are built early and then falls off as either one is pushed late. The red dot marks the optimum. There is a pronounced ridge, not a flat plateau, which shows that timing matters a great deal. Because farms are interchangeable, the surface is also symmetric about the diagonal.
Panel 2, the 3D trajectories. Each curve traces turn, population and food stock together. The optimal plan keeps the stock low in the early turns, because every unit of food is being invested in construction, and then lets the stock climb as the farms come online. The all-late strategy collapses toward zero population, and the no-farm strategy stays pinned at the starting point.
Panel 3, population over time. This is the most direct comparison. The optimal plan overtakes the evenly spaced plan and ends clearly above it. The strategy that builds everything at turn 1 is the surprise. Paying for five farms at once leaves nothing to feed the population, and it ends almost where it started.
Panel 4, marginal value of each farm. The final population rises sharply with each of the first few farms and then flattens. The fourth farm still helps, while a fifth adds nothing, because by then the village already grows at its maximum rate and extra food is wasted to spoilage. This is why the optimal plan contains four farms and not five.
Panel 5, food balance. Production is a staircase that rises each time a farm completes, and demand is a smooth exponential curve. Yellow dotted lines mark construction starts and cyan dashed lines mark production starts. Each new farm is scheduled to arrive just before demand would overtake supply, so shortages are avoided without paying for capacity long before it is needed.
Panel 6, distribution of all plans. Most of the $53{,}130$ plans cluster at poor outcomes, and the optimum sits at the far right tail. A randomly chosen schedule is very unlikely to be good, which shows why a systematic search is worth the effort.
5. Console Output
Number of candidate plans : 53,130 Search time : 0.177 sec Optimal build turns : [1, 3, 6, 9] Final population (turn 20): 179.3 Best with 0 farm(s): turns [] -> population 50.0 Best with 1 farm(s): turns [5] -> population 114.2 Best with 2 farm(s): turns [1, 2] -> population 149.8 Best with 3 farm(s): turns [1, 3, 6] -> population 168.6 Best with 4 farm(s): turns [1, 3, 6, 9] -> population 179.3 Best with 5 farm(s): turns [1, 3, 6, 9, 11] -> population 179.3 Optimal : final population 179.3 All at turn 1 : final population 53.9 Evenly spaced (1,4,7,10,13) : final population 167.1 All late (12-16) : final population 3.3 No farms : final population 50.0
6. Discussion
The exhaustive search shows that the best schedule is a staggered one, with farms started at turns $1, 3, 6$ and $9$. Three lessons come out of it.
- Build early, but not all at once. The first farm goes up at turn 1 because its payback is long and the population is still small enough to absorb the cost. Dumping every farm into the first turn is catastrophic, since the combined cost starves the population before any farm produces.
- Spacing follows the delay. The gaps between builds (2, 3 and 3 turns) are close to the 3-turn production delay. Each farm’s construction cost is paid while the previous farm is still not producing, and the schedule is tuned so that the food dip never becomes deadly.
- Stop at the right number. The marginal value of capacity drops to zero once growth is limited by the maximum growth rate and not by food. Building a fifth farm only burns resources.
The same method scales to richer settings. You can raise KMAX, add several facility types, or make the cost depend on the current population. When the plan space becomes too large to enumerate, dynamic programming or a genetic algorithm can replace the brute-force search, but the vectorized simulator can be reused unchanged as the evaluation function.













