Evolving a Farmer: Building an Agent to Play Kaggriculture

Table of Contents

Kaggriculture is a different kind of Kaggle competition. There is no dataset to download and no CSV to submit. You submit an agent: a Python function that, each turn, receives the state of a two-player farming sim and returns actions like buy seeds, plant, water, harvest, raise animals, trade on the market. Over a 30-day season of 720 turns, whoever has the most money in the bank wins. Your agent is scored by playing games against everyone else’s.

The submission that wouldn’t run

My first attempt didn’t even get a score. It came back ERROR. The cause was not the strategy but a quirk of how the game framework loads your code: it runs your file and grabs the last function defined as the agent. My file happened to end with a little movement helper, so the framework called that as the agent and crashed with “missing 2 required positional arguments.”

The fix was one of those satisfying, humbling one-liners: define every helper first, and put agent() last. That alone took the submission from ERROR to a real leaderboard score.

Then I watched it lose every game

With the environment installed locally, I wrote a benchmark that plays my agent against the framework’s built-in starter agent many times, alternating who goes first, spread across CPU cores so a hundred games take seconds instead of minutes.

The result was a reality check. My greedy agent lost every single game, and finished below the $3,000 it started with. It was buying seeds and land it never earned back, never raising animals (the steadiest income in the game), never planting the high-value melon, and dumping its entire harvest onto the market every turn, which, in a game where prices crash as you sell, is close to the worst thing you can do.

The lesson was clear: the bottleneck was the strategy, not the speed of the code. And a game agent, unlike a big neural net, is not something a GPU helps with. It runs one quick turn at a time on the competition’s own hardware. Where my machine’s cores actually help is in searching for a better strategy.

From hand-tuning to a genome

There are maybe a dozen decisions that define how this agent plays: how many wheat seeds to keep, at what bank balance to start growing carrots or tomatoes or melons, when to buy each new plot of land, when to invest in a goose or a cow, what fraction of a harvest to sell each turn, a floor price below which to just hold, whether to fertilize, whether to pamper the animals for a yield bonus.

Hand-tuning a dozen interacting numbers is a losing game. So I turned every one of them into a gene, a number the agent reads to decide what to do, and let a computer tune them for me.

Evolution does the tuning

A genetic algorithm is a wonderfully simple idea. Start with a population of random agents. Score each one by how much money it makes (I play several games per agent, on both sides, in parallel). Keep the best few unchanged. Breed the rest by mixing two good agents’ genes and adding a little random mutation. Repeat. Generation after generation, the average agent gets better, because the good genes survive and the bad ones don’t.

It is natural selection for farming strategies, and my 24 cores are the environment they compete in. Just switching from the greedy agent to a richer, gene-driven one, with animals, melon, and restrained selling, already roughly doubled the money before evolution even started.

What I’m watching for

The interesting part is not just the final number, it’s the shape of the strategy the evolution discovers. Does it learn to hold premium goods until prices recover? Does it find the right moment to pivot from crops into livestock? Does buying land ever pay for itself in a 30-day season? I’m logging the best genome every generation, so the story is the progression itself.

The evolution worked, against the wrong opponent

The genetic algorithm did its job: after 23 generations and about 6,600 self-play games, the best genome beat the built-in starter agent 88 to 100% of the time. I baked it into a submission and it scored 243.7 on the leaderboard, a real step up from the score the loader fix alone had earned.

Then I looked at the rank: roughly 6,940 out of 7,491. Bottom 8%. The median competitor scored ~762; I was less than a third of that.

The problem was subtle and, in hindsight, obvious. I had trained my agent to beat one specific, weak opponent, and it got very good at exactly that. But starter is a sparring partner, not a champion. Beating it perfectly only bankrolls about $4,000, while the leaderboard scores you against real submitted agents that earn far more. Running the same evolution longer wouldn’t have helped: it was acing the wrong exam.

Chasing the wrong lever: strategy vs. execution

I spent a while building “smarter” agents from economic theory: an animal-engine that rushes livestock, a melon baron that farms the highest-value crop, a market-maker that sells into town demand. Every one of them lost, some finishing below their starting money.

So I traced an actual game, tile by tile, and got a genuine surprise: none of my agents were really farming. Tiles sat empty and rotted into weeds because the units wandered instead of working. My timid champion “won” only by hoarding cash and avoiding losses. The binding problem wasn’t strategy at all, it was operational competence. An agent that simply kept every tile planted and watered, and harvested on time, would beat everything I had.

That agent, units that always move to the nearest thing that needs doing, beat my evolved champion 16 out of 16, roughly $5,500 to $3,500. One routing fix outperformed 30,000 games of evolution. The lesson stuck: fix execution before optimizing strategy.

Watching the winners

The real breakthrough came from watching replays of the top players. They finish with $63,000 to $88,000, roughly fifteen times my best at that point. And they all do the same thing: build a herd of a dozen-plus cows and sheep, hire a fresh farm hand almost every turn to buy the labor to tend them, and sell milk, wool, and, surprisingly, fertilizer continuously. The animals are a perpetual engine: buy once, harvest forever. Their money stays near zero until about day nine, then explodes.

This overturned my earlier conclusion that “capital strategies underperform.” They don’t. The animal herd is the game. My attempts had just executed it badly.

The mechanic everyone missed

Building the herd engine, my first two versions busted in exactly the same way every earlier animal agent had. Tracing the game revealed two rules buried in the engine’s source that the summary docs only hinted at:

Once units ferried wheat out to the herd and carried animals out to populate it, and I grew the herd one animal at a time, only while everything was fed, the money curve finally matched the winners. Near-broke through the setup, then a compounding explosion to $20,000, $40,000, and beyond. It beat the previous champion 12 out of 12 and roughly septupled the money. The leaderboard rating jumped from 251 to 472.

The highest-value fix was defensive

Even then, profiling showed I still trailed the top players. I tried two “earn more” ideas, selling premium goods in a careful trickle to protect the price, and expanding onto more land for a bigger herd. Both lost head-to-head. Trickling just let the opponent grab the good prices first; expanding spread the herd so thin the units couldn’t feed it, and animals starved on the far tiles.

The real leak was measurable: my herd peaked around 11 animals but ended around 7. I was losing two to four animals a game to starvation, and the game-to-game money swings tracked almost exactly with how many animals survived. Each escaped cow is a $400 asset plus all its future milk, gone.

The fix was to treat an animal that had already missed one feeding as an emergency: the moment any unit is carrying wheat, it drops everything and runs to the nearest at-risk animal. The result was zero escapes, the full herd alive at the end of every game, a 70% head-to-head win rate over the previous version, and an average near $45,000 with peaks into the top-player range.

The lesson I keep relearning: the biggest gain wasn’t earning more, it was not losing the assets I’d already paid for. Protect the compounding engine first; scale it second.

Reading the market instead of guessing it

With the herd stable, the next question was timing: could I sell before prices crash? The tempting answer is to learn the price distribution from past games. But the game’s own rules make that unnecessary. The price of every good is a fixed function of how much of it is sitting in the market, and I can read the current price and inventory every single turn.

So I watched a real game and found each good behaves differently. Fertilizer, a free byproduct everyone dumps, decays all season from $100 toward $10, so I sell it the instant I have it. Wheat and wool actually appreciate, because the town’s shops keep draining them below their equilibrium supply, so I hold them and sell surplus near their highs. Milk is the volatile one: dump it and it craters to $7, hold it and it recovers to $70+. It’s the only good where timing genuinely pays.

The fix was a small price memory that tracks each good’s recent high. Premium goods sell in full when the price is near that high, sell half at a mediocre price, and hold when it’s depressed, unless the shed is about to overflow, in which case I sell anyway, because a discarded unit is worth nothing. This beat the previous version 77% of the time over 30 games, with a real money edge this time.

The takeaway: I didn’t need machine learning on price history. The market is a known curve, so the win came from reading it, not modeling it. This was a fun project because unlike most Kaggle projects, it wasn’t just a model, it felt more like game programming. And working with agents on something like this is not something I’ve done very much. Initially, I was excited about my genetic algorithm idea and was glad that it worked, but it was humbling that almost everyone else outperformed my results. It’s really the same learning I should have had from the titanic project: Do your research first and then optimize. Otherwise, you’re spending your time optimizing the wrong model or starting in the wrong spot meaning you’ll end up in a local min you can’t evolve out of.