How to make a tower defense game with AI
Give a player somewhere to build and they will eventually wall the route off completely. Everything else in a tower defence game depends on which answer you pick for that.
Jump to a section
Ask for a fixed route across a grid, towers that may only sit on marked plots beside it, and a button that releases the next wave. That one restriction is the whole design decision, and it is the reason the build works on the first try. The alternative, letting the player build on any tile, needs a route search on every single placement before it is safe.
Not maliciously. A player who notices that walls help will keep adding walls until there is no way through, because that is what the rules told them to do. At that moment either the pathfinder returns nothing and the wave stops forever, or something falls back to walking in a straight line and the towers stop mattering. Both are the end of the game.
Four steps to a wave worth defending#
You are checking that a leak costs a life and that the counter actually drops. Half of first builds forget the second part.
Put towers everywhere a tower is allowed. Nothing should be able to stop an enemy reaching the base.
They should still be survivable, or close to it. If they are not, the opening is doing the job of a later wave.
Two towers that behave differently is already a decision. A third one before the pacing works is just more to balance.
Build a tower defence game as ONE self-contained .html file. No
frameworks, no images, no libraries.
MAP: a grid drawn on a canvas. A fixed route of dark tiles runs from a
gap in the left edge, bends twice, and ends at a base on the right.
The lighter tiles alongside it are build plots. Towers go on plots
only, never on the route, so the route can never be closed.
ENEMIES: they walk the route tile by tile towards the base, each with
health and a speed. One reaching the base costs a life.
TOWERS: two kinds, both placed by clicking a free plot. A gun that
fires at whichever enemy in range is furthest along the route, and a
frost tower that slows everything in range instead of hurting it.
Show the range as a ring while a plot is being chosen.
MONEY: a kill pays a little, finishing a wave pays more. Show the
balance and dim any tower the player cannot afford.
WAVES: a button releases the next wave and nothing moves until it is
pressed. The first wave is a single slow enemy. The next two add a few
more of the same kind. From the fourth wave onwards, give enemies more
health rather than only sending more of them.
HUD: lives, money, wave number, and the name of the tower under the
cursor.
Write a comment above the placement code saying that towers are
restricted to plots so the route cannot be sealed, so that a later
change does not remove the guarantee by accident.
Derive all movement, firing and slowing from the number of seconds
that elapsed since the previous frame, held to 0.05 at the most, so a
tab left in another window does not deliver a whole wave in one step.
Put canvas { touch-action: none; } in the stylesheet so tapping a plot
on a phone does not drag the page around. Gather every number the
game uses into a single CONFIG object at the head of the script: tower
cost, damage, range, rate of fire, how much frost slows, enemy health
per wave, enemy speed, starting money and starting lives.
The MAP paragraph is the load-bearing one. Change the tower stats, the money and the wave curve as much as you like. If you later want building on any tile, you are changing the design and not a number, and the section below says what that costs.
The wall-off rule, and what breaks without it#
Free building is the version most people picture, because shaping the route is the best part of the genre. It is also where first builds die. The player blocks a gap, the route search comes back with nothing, and the code has no plan for that answer.
What you see depends on which shortcut the code took. A search that returns an empty list usually leaves enemies standing still, so the wave never ends and the next one never starts. A search that falls back to heading towards the base in a straight line sends them through the towers, which makes the entire build phase pointless. Neither is a bug you can patch later, because the rule about sealing the map is a rule about the game.
There are only two honest answers. Either placement is restricted so that sealing is impossible, or every placement is tested and refused when it would seal. Anything in between is a promise you cannot keep.
| Fixed route and plots | Build on any tile | |
|---|---|---|
| Can the route be sealed | No, the layout forbids it | Only while every placement is tested |
| What it needs | A list of route tiles | A grid search run on each attempt |
| What the player decides | Which plot and which tower | The shape of the route as well |
| Where it still goes wrong | Levels start to feel alike | An enemy stranded partway along |
| Build this first | Yes | In the second version, once waves work |
Both are real designs and plenty of finished games use the left-hand one. The left-hand one also exists by this evening.
If you do go for free building, one detail is missed almost every time. When a tower goes up, the enemies already walking need new routes too, not just the ones yet to spawn. Test the route from the spawn point and the game looks fine, while an enemy halfway across finds its next tile walled and stops. Ask for the route to be recalculated from each live enemy's own tile, and for placement to be refused if any of them would be stranded.
Wave pacing starts almost free#
The first waves are not difficulty. They are the tutorial, and they are the only tutorial most browser games get. A player who loses before working out that towers shoot by themselves does not conclude that the game is hard. They conclude that it is broken, and they are half right.
After the opening, the lever to reach for is enemy health rather than enemy count. Sending more of the same thing makes waves longer without making them harder, and a long wave is just waiting. Tougher enemies force a decision about whether the current towers are still good enough.
- Let the player start the wave. A timer that releases the next wave while they are still choosing a plot turns thinking into panic, and the genre is about thinking.
- Pay for finishing a wave, not only for kills. Otherwise a player who loses an enemy loses the money to replace the tower that failed, and a bad wave becomes a death spiral.
- Show the next wave before it arrives. Even a line of text naming what is coming turns the gap between waves into a planning phase instead of a pause.
- Give several lives, not one. A single leak ending the run punishes the exact experiment the player needs to make to learn anything.
Targeting, range and what to put on screen#
Once pathing is settled, the thing players argue about is which enemy a tower shoots. Ask for the wrong rule and towers feel unreliable even when the numbers are right.
| Targeting rule | How it plays | Use it for |
|---|---|---|
| Furthest along the route | Matches what the player wants | The default for every tower |
| Nearest to the tower | Towers fuss over new arrivals | Short range towers near the spawn |
| Lowest health | Tidies up, misses the leaker | A support tower, deliberately |
| Whatever the loop found first | Looks random and feels broken | Nothing |
Pick the rule on purpose. The last row is what you get when nobody picks, because it depends on the order enemies happen to sit in the array.
Range needs to be visible while a plot is being chosen and invisible afterwards. A ring drawn on every tower all the time buries the map. A ring drawn on none of them leaves the player guessing, and guessing about range is guessing about the only thing a placement decides.
One more display choice earns its keep. Put a thin health bar above each enemy rather than floating damage numbers. Numbers tell the player what one shot did, which they can work out anyway. A bar tells them whether this wave is going to get through, which is the question they actually have.
🏰Tower defence games written by AI
Common questions#
Can AI make a tower defence game?
Yes, and the fixed route version comes out working more often than most genres do. Ask for a set route with build plots beside it. The part that needs your attention is not the code, it is deciding in advance whether the player can block the route at all.
Why have my enemies stopped moving?
Almost certainly because a tower closed the last gap and the route search came back with nothing. Either restrict towers to plots so it cannot happen, or test each placement on a copy of the grid and refuse the ones that would seal the map.
Why do enemies walk straight through my towers?
The route search failed and something fell back to heading for the base in a straight line. It is the same cause as enemies freezing, handled differently. Fix the cause rather than the symptom, because the fallback makes the build phase meaningless.
Should I let players build anywhere?
Eventually, but not in the first version. Free building means a route search on every attempted placement, plus a fresh route for every enemy already on the map. Get waves, money and towers working on a fixed route first, then change the rule.
How hard should the first waves be?
Survivable even if the player does nothing clever. The opening waves teach where to click, that towers fire on their own, and that coverage matters. Something that can be lost belongs a few waves later, once all three of those are known.
Should waves get bigger or tougher?
Tougher. More of the same enemy only makes a wave take longer, and waiting is not difficulty. Raising health and speed forces the player to ask whether their current towers are still enough, which is the decision the genre is built on.
Where to go next#
Once a wave has got through and you have said one more go out loud, publish it. It gets its own page with the model and the prompt that made it, and a leaderboard for how far people got.
The general method is in how to make a game with AI. If you want the towers to make choices rather than just fire, the scoring approach in the strategy guide is the same idea applied to an opponent. Drawing and grids are covered in the 2D guide and ready prompts are in the prompt guide. The tower defence games here will show you what pacing other people settled on.
Built something? Put it on Agent Games.
Publishing takes a file and a minute. Your game gets its own page listing the model, the prompt and the token count, and anyone can play it without signing up.
Read next