HTML5 Tower Defense: Make Each Enemy Resolve Exactly Once

An enemy reaches the endpoint on the same update that removes its last health point. The prototype awards a coin and removes a life.

Elsewhere, an empty screen triggers victory even though two scheduled enemies have not spawned. Both failures come from reconciling a picture rather than the enemy's state.

An HTML5 tower defense prototype needs explicit build, targeting, cooldown and resolution rules before additional maps or upgrades. This original one-pad model makes those rules small enough to trace. The manuscript supplies a complete implementation prompt and expected fixtures; the companion provides the one-pad prototype alongside those expected fixtures.

One Pad Defense — Implement path progress, target eligibility, cooldown and one-time kill/leak reconciliation in a playable local prototype.
One Pad Defense — Implement path progress, target eligibility, cooldown and one-time kill/leak reconciliation in a playable local prototype.
Open the full example ↗

Start with a bounded field and wave

Use an original 320 × 200 logical field. Enemies follow the straight center path from (0,100) to (300,100). Each stable ID starts with 2 HP and moves at 30 logical pixels per simulation second.

Enemy Spawn time Initial HP Resolution
E1 0 seconds 2 Pending until killed or leaked
E2 2 seconds 2 Pending until killed or leaked
E3 4 seconds 2 Pending until killed or leaked

There is one build pad at (150,60), costing 2 coins. Start with 3 coins and 2 lives. A successful build leaves 1 coin and one tower. Repeating Build on the occupied pad leaves both unchanged; insufficient funds likewise cannot deduct coins or create a tower.

For this prototype, build only while Ready, before Start Wave. Start is allowed once per reset, with or without a tower; it sets the simulation clock to zero and spawns E1. There are no upgrades, sales, alternate pads or new waves.

Use enemy centers for path/range calculations, not sprite edges. Visual scaling must retain the logical coordinates.

Separate simulation updates from drawing

MDN discusses game-loop timing, update/render separation and choices when a browser stops advancing callbacks. Adopt those timing concepts, without copying its example code or treating it as proof of this tower's gameplay. MDN: Anatomy of a Video Game

The proposed model uses fixed 0.1-second simulation steps. Movement per step is 30 × 0.1 = 3 pixels. One animation scheduler draws the current state; drawing does not fire a shot or advance a spawn.

Limit each frame to at most 10 steps/1 simulation second of accumulated work, discarding excess elapsed time as a slowdown policy. This is an original bound for a tiny prototype, not a performance benchmark. Hidden pages and explicit Pause advance no simulation time; Resume starts a fresh timestamp without catching up the paused interval.

Within a step, establish due spawns and their age/progress, choose any due shot, reconcile kills, then reconcile remaining living endpoint arrivals. Finally evaluate terminal state. E2 spawned at t=2 has progress zero at that instant, not a full extra step of movement.

Filter targets before applying priority

The tower's radius is 70, inclusive. A target must be spawned, alive, unresolved and within center distance 70. Pending IDs and already killed/leaked IDs cannot be selected.

The range test is (x−150)² + (100−60)² ≤ 70². At x=90, the squared distance is 5,200, outside 4,900. At x=93 it is 4,849, inside. These are original mathematical fixtures, not a claim that the implementation has been run.

Among eligible enemies, choose the largest path progress; break a tie by ascending stable ID. For an isolated target-selection fixture with living enemies at x=150 and x=200, both are in range and x=200 wins. An enemy farther ahead but out of range is excluded before sorting.

No range or target choice changes HP until a shot is due. Show the chosen ID, distance/range and HP in text so the decision can be inspected beside the field.

Advance cooldown in simulation time

A build at pre-wave time zero makes the earliest permitted shot t=1. Each shot deals 1 damage and sets the next allowed shot to actual shot time plus 1 simulation second.

If no eligible target exists when cooldown is ready, remain ready; do not spend a shot or continually postpone the next opportunity. On the first step with an eligible target, fire once. Rendering additional frames at the same simulation time cannot add damage.

With the tower built before Start, E1 first enters range on the t=3.1 step at x=93. The expected first shot changes its HP from 2 to 1. At t=4.1, E1 is at x=123 and the second shot kills it.

Under the same proposed step/order rules, E2 receives shots at t=5.1 and 6.1; E3 receives shots at t=7.1 and 8.1. This is a planned trace to test against later code, not a performed playthrough.

Reconcile kills and leaks as exclusive outcomes

A killed enemy transitions once to Killed, leaves the active target set and awards exactly 1 coin. Rechecking that ID must not award another coin.

A still-living enemy at progress 300 transitions once to Leaked, leaves the active set and removes 1 life. Clamp lives at zero; a repeated reconciliation cannot subtract again.

The normal pad cannot reach an enemy at the endpoint. A defensive reconciliation test can nevertheless supply an already-zero-HP endpoint record: resolve it as killed once, then exclude it from the alive-leak pass. That test exercises state integrity; it does not authorize an out-of-range endpoint shot.

Lose as soon as lives become zero. Stop further gameplay and scheduled spawns after that terminal decision. Win only when all three IDs have spawned and resolved and lives remain positive. An empty active list at t=1 is not victory.

The prebuilt-tower trace predicts three kills, 4 coins after the initial build/rewards and 2 lives. Without a tower, E1 reaches the endpoint at t=10 and E2 at t=12; the second leak makes lives zero. E3 need not leak before the loss. These expected results require runtime verification.

Keep controls and reset outside the drawing

Use native Build Pad, Start Wave, Pause, Resume and Reset buttons, with text for coins, lives, simulation time, each enemy status and cooldown. Do not make clicking a canvas the only build method.

Build is disabled outside Ready or after occupancy. Start cannot create duplicate E1/E2/E3 schedules. Pause/hidden state clears pending input; Resume cannot start a second scheduler. Terminal state ignores build, start and resume until Reset.

Reset cancels the old callback generation and restores Ready, coins 3, lives 2, empty pad, all three unspawned IDs, time zero and no cooldown. A stale callback from the previous run must not move, spawn, reward or leak anything.

Actual keyboard access, focus, original graphics and narrow layout remain pending. The field's 320 × 200 logical dimensions are not a fixed article-container width.

Copy this prompt to prepare the original prototype

Create one complete, self-contained US-English HTML companion for “One Pad Defense”. Return the full HTML document, with inline CSS and any JavaScript needed for the local interactions. Use the original scenario, named records, numbers and expected cases below.

Design the page for this task: use clearly labeled input or source records, a readable result or worked example, and an adjacent explanation of the evidence. Use a restrained visual hierarchy, left-aligned text, readable tables or stacked records, and a responsive layout at 720px and 360px. Provide meaningful labeled controls for Build pad · 2 coins; Start wave; Pause; Resume; Reset; Advance 1.0 s while paused; Resolve wave without animation. Use keyboard-accessible native controls and visible focus. Keep the complete content readable without an external dependency.

The following brief supplies the substantive content and constraints. Native-format requests describe the material to represent or copy manually; this HTML must not pretend to create DOCX, XLSX, PDF, PPTX, H5P or another native file, run Python/Flask/Django/Snowflake/Power BI, connect a live service, send messages, or perform an authorized real-world action. Where the task requires a native source, actual observation or separate approval, retain that requirement and leave unsupplied evidence blank.

Create complete original native HTML/CSS/JavaScript source and a manual test matrix for this one-pad tower-defense prototype. Reference https://developer.mozilla.org/en-US/docs/Games/Anatomy for timing/update separation only; do not copy source code/maps/assets. Use neutral original graphics, no libraries/network/accounts/storage. Source/runtime/visual verification must precede any working-game claim.

Logical field 320 × 200. Enemy center path (0,100)→(300,100); speed 30 logical pixels/second; stable E1/E2/E3 spawn at simulation times 0/2/4, HP 2 each. Start with 3 coins/2 lives. Pad (150,60), cost 2, range 70 inclusive. Build only in Ready before wave, once: 3−2=1; occupied, insufficient-funds or invalid-state attempt changes nothing. Start Wave allowed once per Reset with or without tower, clock zero and E1 spawned; no new waves, upgrades or sales.

Fixed step 0.1 seconds, 3 pixels per enemy step. One scheduler; maximum 10 steps/1 simulation second per frame, discard excess as documented slowdown policy. Drawing never updates damage/resources/spawns. Due spawns enter at age zero exactly; progress = 30 × (current simulation time−spawn time), bounded at 300. Step: establish due spawns/progress, due shot, kills, remaining living leaks, terminal check.

Eligible targets are spawned, alive and unresolved with squared center distance ≤4,900. Sort by largest path progress then ascending ID. At x=90, distance²=5,200, outside; x=93, distance²=4,849, inside. Living x=150/x=200 fixture selects x=200; exclude out-of-range candidates first.

Earliest shot 1 simulation second after build at time zero. Damage 1; next due at actual shot time+1. No target means stay ready, no phantom shot/reset of cooldown. One shot per due step, no per-render firing. Prebuilt planned trace: E1 shots at 3.1/4.1 and killed; E2 at 5.1/6.1 and killed; E3 at 7.1/8.1 and killed; coins 4/lives 2. Verify, do not claim performed.

HP ≤0 transitions to Killed once: remove active ID, add 1 coin once. Remaining alive progress ≥300 transitions to Leaked once: remove ID, subtract 1 life, clamp at zero. No ID can both kill/reward and leak. Endpoint HP=0 synthetic reconciliation fixture tests this rule, not a legal out-of-range shot. Lose immediately at zero lives and stop; win only when all three spawned/resolved with positive lives. Empty active list before future spawns never wins. Without a tower, expect E1 leak at 10 and E2 leak at 12 seconds → loss; pending events cannot act after terminal.

Native Build Pad/Start Wave/Pause/Resume/Reset with DOM coins/lives/time/enemy HP/status/range/cooldown. Keyboard-operable pad, no canvas-only control. Pause/hidden stops simulation and clears pending input; Resume uses a fresh timestamp, no catchup and one loop. Terminal ignores gameplay. Reset cancels old callback generation; restore Ready, coins 3/lives 2/no tower/all IDs unspawned/time zero/no cooldown. Stale callbacks cannot mutate state.

Test build cost/repeat/insufficiency, boundary70, eligibility/priority/ties, HP2 two shots/cooldown/no-target readiness, one-time kill/leak, synthetic HP0 endpoint, future spawn win guard, expected tower/no-tower traces, pause/Resume/hidden/Reset and stale callbacks. Test keyboard/focus, production article width and360px with text outcomes. Finish a separate optional NOS reading copy using an optional Explore NOS link without feature promises; actual scripts/playability/hosting must be tested. No captures/publication performed by this manuscript.

COMPLETE AUTHORED SCENARIO AND EXPECTED CASES
The following is the supplied reading/teaching/calculation record to represent in the companion. Preserve its particular content, examples, source references and unknowns. Wording about a future native implementation refers to that native task, not permission to omit this HTML companion.

# HTML5 Tower Defense: Make Each Enemy Resolve Exactly Once

An enemy reaches the endpoint on the same update that removes its last health point. The prototype awards a coin and removes a life. Elsewhere, an empty screen triggers victory even though two scheduled enemies have not spawned. Both failures come from reconciling a picture rather than the enemy's state.

An HTML5 tower defense prototype needs explicit build, targeting, cooldown and resolution rules before additional maps or upgrades. This original one-pad model makes those rules small enough to trace. The manuscript supplies a complete implementation prompt and expected fixtures; the companion provides the one-pad prototype alongside those expected fixtures.

## Start with a bounded field and wave

Use an original 320 × 200 logical field. Enemies follow the straight center path from (0,100) to (300,100). Each stable ID starts with 2 HP and moves at 30 logical pixels per simulation second.

| Enemy | Spawn time | Initial HP | Resolution |
|---|---|---|---|
| E1 | 0 seconds | 2 | Pending until killed or leaked |
| E2 | 2 seconds | 2 | Pending until killed or leaked |
| E3 | 4 seconds | 2 | Pending until killed or leaked |

There is one build pad at (150,60), costing 2 coins. Start with 3 coins and 2 lives. A successful build leaves 1 coin and one tower. Repeating Build on the occupied pad leaves both unchanged; insufficient funds likewise cannot deduct coins or create a tower.

For this prototype, build only while Ready, before Start Wave. Start is allowed once per reset, with or without a tower; it sets the simulation clock to zero and spawns E1. There are no upgrades, sales, alternate pads or new waves.

Use enemy centers for path/range calculations, not sprite edges. Visual scaling must retain the logical coordinates.

## Separate simulation updates from drawing

MDN discusses game-loop timing, update/render separation and choices when a browser stops advancing callbacks. Adopt those timing concepts, without copying its example code or treating it as proof of this tower's gameplay. [MDN: Anatomy of a Video Game](https://developer.mozilla.org/en-US/docs/Games/Anatomy)

The proposed model uses fixed 0.1-second simulation steps. Movement per step is 30 × 0.1 = 3 pixels. One animation scheduler draws the current state; drawing does not fire a shot or advance a spawn.

Limit each frame to at most 10 steps/1 simulation second of accumulated work, discarding excess elapsed time as a slowdown policy. This is an original bound for a tiny prototype, not a performance benchmark. Hidden pages and explicit Pause advance no simulation time; Resume starts a fresh timestamp without catching up the paused interval.

Within a step, establish due spawns and their age/progress, choose any due shot, reconcile kills, then reconcile remaining living endpoint arrivals. Finally evaluate terminal state. E2 spawned at t=2 has progress zero at that instant, not a full extra step of movement.

## Filter targets before applying priority

The tower's radius is 70, inclusive. A target must be spawned, alive, unresolved and within center distance 70. Pending IDs and already killed/leaked IDs cannot be selected.

The range test is (x−150)² + (100−60)² ≤ 70². At x=90, the squared distance is 5,200, outside 4,900. At x=93 it is 4,849, inside. These are original mathematical fixtures, not a claim that the implementation has been run.

Among eligible enemies, choose the largest path progress; break a tie by ascending stable ID. For an isolated target-selection fixture with living enemies at x=150 and x=200, both are in range and x=200 wins. An enemy farther ahead but out of range is excluded before sorting.

No range or target choice changes HP until a shot is due. Show the chosen ID, distance/range and HP in text so the decision can be inspected beside the field.

## Advance cooldown in simulation time

A build at pre-wave time zero makes the earliest permitted shot t=1. Each shot deals 1 damage and sets the next allowed shot to actual shot time plus 1 simulation second.

If no eligible target exists when cooldown is ready, remain ready; do not spend a shot or continually postpone the next opportunity. On the first step with an eligible target, fire once. Rendering additional frames at the same simulation time cannot add damage.

With the tower built before Start, E1 first enters range on the t=3.1 step at x=93. The expected first shot changes its HP from 2 to 1. At t=4.1, E1 is at x=123 and the second shot kills it.

Under the same proposed step/order rules, E2 receives shots at t=5.1 and 6.1; E3 receives shots at t=7.1 and 8.1. This is a planned trace to test against later code, not a performed playthrough.

## Reconcile kills and leaks as exclusive outcomes

A killed enemy transitions once to Killed, leaves the active target set and awards exactly 1 coin. Rechecking that ID must not award another coin.

A still-living enemy at progress 300 transitions once to Leaked, leaves the active set and removes 1 life. Clamp lives at zero; a repeated reconciliation cannot subtract again.

The normal pad cannot reach an enemy at the endpoint. A defensive reconciliation test can nevertheless supply an already-zero-HP endpoint record: resolve it as killed once, then exclude it from the alive-leak pass. That test exercises state integrity; it does not authorize an out-of-range endpoint shot.

Lose as soon as lives become zero. Stop further gameplay and scheduled spawns after that terminal decision. Win only when all three IDs have spawned and resolved and lives remain positive. An empty active list at t=1 is not victory.

The prebuilt-tower trace predicts three kills, 4 coins after the initial build/rewards and 2 lives. Without a tower, E1 reaches the endpoint at t=10 and E2 at t=12; the second leak makes lives zero. E3 need not leak before the loss. These expected results require runtime verification.

## Keep controls and reset outside the drawing

Use native Build Pad, Start Wave, Pause, Resume and Reset buttons, with text for coins, lives, simulation time, each enemy status and cooldown. Do not make clicking a canvas the only build method.

Build is disabled outside Ready or after occupancy. Start cannot create duplicate E1/E2/E3 schedules. Pause/hidden state clears pending input; Resume cannot start a second scheduler. Terminal state ignores build, start and resume until Reset.

Reset cancels the old callback generation and restores Ready, coins 3, lives 2, empty pad, all three unspawned IDs, time zero and no cooldown. A stale callback from the previous run must not move, spawn, reward or leak anything.

Actual keyboard access, focus, original graphics and narrow layout remain pending. The field's 320 × 200 logical dimensions are not a fixed article-container width.



Implement the local companion rather than returning a text-only plan. Preserve every numerical fixture and the distinction between illustrative expectations and actual evidence. Any native-runtime or classroom tests mentioned above remain tests to perform in the proper environment; do not mark them passed. Keep edits and practice responses in this open page only, without claiming persistent storage. Provide invalid/missing-input feedback and reset behavior that agree with this specific brief. Do not claim accessibility certification, learning gains, real approvals or test results that were not observed.

Review: a reading copy of the resolution trace

Keep the native source and test ledger together. Use the companion to show range, cooldown and enemy outcomes beside their original fixtures.

Verify actual script execution, controls, timing and layout before showing a playable hosted example. A saved game explanation does not establish that its shots or reset work.

Explore NOS

The useful prototype gives each enemy one traceable outcome and leaves future spawns in the victory condition.

Keep reading