Ecosystem Evolution Simulator
Single-file artificial-life simulator with predator/prey/food energy dynamics, a round rotating 3D map, cute animated agents, live controls, and real population graphs.
<instructions>
Build the best living-ecosystem simulator you are capable of building. A real, running artificial life world — predators, prey, and food — governed by an energy economy, where populations rise, crash, and oscillate on their own. Not a screensaver of random dots. A genuine simulation the user can steer with a control dashboard, run for thousands of generations, and read the results of on live graphs.
The user is a "god" watching a petri dish. They set the rules (how fast food grows, how fast prey breed, how deadly predators are), press play, and watch what emerges. Then they read the story of what happened in the charts.
</instructions>
<mindset>
Treat this as the project you'd submit if your reputation depended on it. The difference between a great submission and a mediocre one here is not visual polish — it's whether the simulation is *actually alive*. A weak implementation makes creatures wander randomly and multiply until the screen is full or empty. A correct implementation produces the classic emergent behavior of real ecosystems: predator and prey populations oscillating out of phase, boom-and-bust cycles, extinctions, and recoveries — none of it scripted, all of it emerging from the rules.
If you're choosing between "looks good" and "behaves correctly," choose correct. The single most important thing you can get right is the energy economy (below). Get that right and the emergent dynamics come for free. Get it wrong and no amount of UI polish will save it.
Push on every axis:
- Simulation correctness (real energy economy, real emergent oscillations, no populations that just explode or flatline)
- Performance (thousands of agents at 60fps — spatial partitioning, not O(n²) neighbor checks)
- Dashboard depth (every rule that matters is a live, labeled control that visibly changes the world)
- Data honesty (the graphs must plot real recorded history, not decorative sine waves)
- Visual clarity (you should be able to *see* a predator chasing prey, a herd fleeing, and creatures pausing to eat)
</mindset>
<the-energy-economy>
This is the heart of the simulation and the thing most implementations get wrong. Every living agent has an `energy` value. This single mechanic is what produces realistic dynamics — populations self-regulate through starvation and reproduction instead of exploding to infinity.
**Food (plants / grass):**
- Grows on the world over time at a configurable rate.
- Does NOT regrow instantly where it was eaten — there is a regrowth delay. (This delay is the stabilizing force behind oscillations. Do not skip it.)
- Has a carrying capacity (max food the world can hold).
**Prey (herbivores):**
- Spend energy every tick to stay alive and move (metabolism).
- Gain energy by finding and eating food.
- Reproduce ASEXUALLY when energy crosses a reproduction threshold: they split, and the energy cost is deducted from the parent (parent and child each get roughly half). No free lunch — reproduction must cost energy, or the population explodes.
- Die when energy reaches zero (starvation) or when eaten.
**Predators (carnivores / "killers"):**
- Same metabolism → they burn energy constantly and must hunt to survive.
- Gain energy by catching and eating prey.
- Reproduce on the same energy-threshold rule.
- Die of starvation when they can't find prey — this is what prevents predators from wiping out all prey. When prey get scarce, predators starve and crash, letting prey recover. That out-of-phase rise and fall is the signature you are trying to produce.
If reproduction is free, or death from starvation doesn't exist, or food regrows instantly, the simulation will NOT oscillate — it will explode or flatline. The three death/birth pressures (starvation, predation, energy-gated reproduction) are non-negotiable.
</the-energy-economy>
<the-three-rates>
These are the headline controls the user explicitly wants, and they must have a real, visible, immediate effect on the running world:
1. **Food rate** — how fast/abundant plant food grows. Low = starvation and prey crashes. High = prey boom.
2. **Reproduction rate** — how readily prey and predators breed (via the energy threshold and/or a fertility multiplier). Tunes how fast populations rebound.
3. **Killer rate** — predator lethality/aggression: hunt range, catch success, how many predators spawn, or how much energy they gain per kill. Low = predators starve out. High = prey get wiped and predators crash after them.
The magic of this simulator is that these three knobs are in tension. There is a narrow band where all three species coexist and oscillate forever; push any knob too far and you get extinction. The user should be able to *feel* that balance by dragging sliders on a live world.
</the-three-rates>
<visual-direction>
The world must feel like a living petri-dish map, not an abstract dot field.
**Map / world presentation:**
- Render the simulation as a round 3D / isometric map or petri dish. It should read as a circular raised terrain/map that the user can click and drag to rotate.
- The round map is not just a visual mask: spawning, food placement, movement, sensing, collision/bounce, and regrowth must respect the circular world boundary.
- The camera/map interaction must be direct: click/touch and drag rotates the map; clicking an agent selects it for inspection.
- Keep the simulation model deterministic and 2D under the hood if useful, but render it with depth, shadows, ordering, scale, and terrain cues so it feels like a 3D map.
**Food:**
- Food should appear as trees with visible green fruit/food on them, not random dots.
- Eaten trees must visibly lose food and then regrow only after the configured delay.
- Food growth must still be governed by the real food rate, regrowth delay, and carrying capacity.
**Creatures:**
- Prey and predators should be cute glossy oval/bean-like characters with simple faces, similar to small animated mascot people. They should not be plain dots, flat circles, or generic balls.
- Use clear visual identities: for example blue/cyan prey, red/pink predators, green fruit/food.
- The characters should look alive: squash/stretch, blink, lean toward targets, show panic/fleeing motion, and face roughly in their movement direction when possible.
**Eating behavior and animation:**
- Eating is not instant. Prey need an eating/wait time when they reach food, and predators need an eating/wait/digest time after catching prey.
- These eating states must affect behavior: while eating, agents pause or slow substantially and cannot immediately chain-eat everything around them.
- Add visible eating animations for both prey and predators: chewing pulses, bite marks, feeding sparkles/crumbs, mouth movement, or a short lock-on interaction with the tree/prey.
- The dashboard must expose prey eating time and predator eating time/cooldown controls, and changing them should affect the running simulation.
</visual-direction>
<baseline-features>
Non-negotiable. The floor, not the ceiling.
**The world & simulation engine:**
- A 2D simulation world rendered as a round rotating 3D/isometric canvas map where agents move, sense nearby food/prey/predators, and act each tick.
- Circular world mechanics: all agents, trees, sensing, spawning, and boundary handling must stay inside the round map.
- Spatial partitioning (grid/quadtree) so neighbor lookups are not O(n²). This is what lets you hit thousands of agents.
- A fixed-timestep simulation loop decoupled from rendering, with a speed control (pause, step, 1×, 5×, 20×, max/turbo where rendering is throttled but the sim keeps running).
- Deterministic, seedable RNG so a given seed + settings reproduces the same run.
**The control dashboard (the "tool"):**
- Live sliders/inputs for: food growth rate, food capacity, food regrowth delay, prey metabolism, prey reproduction threshold, prey vision range, prey speed, prey eating time, predator metabolism, predator hunt range, predator catch chance, predator eating time, energy gained per kill, initial population counts, world size/map radius, and a global RNG seed.
- Changing any control affects the live simulation immediately (or on next tick) — no reload required.
- Buttons: Start / Pause / Step / Reset, Randomize settings, and presets ("Balanced", "Predator apocalypse", "Prey paradise", "Fragile equilibrium", "Ice age / low food").
- Live readouts: current tick/generation, live counts of each species, total births/deaths, average energy, average lifespan.
**The graphs (the payoff):**
- A LIVE, scrolling population-over-time chart drawn as the sim runs, plotting food / prey / predator counts together on one mixed graph with the same time axis. Do not split it into three separate horizontal graph bands.
- Because food, prey, and predator counts can be very different magnitudes, use a readable overlay strategy such as per-series normalization, dual-scale labels, or labeled max/current markers so all three lines are visible at once.
- Draw the chart yourself from recorded history data (a rolling time-series buffer). It must reflect the actual run.
- An "end of run" / summary view: when the user stops (or a species goes extinct, or a generation cap is hit), show the full-run charts plus stats — peak populations, number of oscillation cycles, extinction events and when they happened, min/max/avg of each population, and a one-line verdict of what happened ("Stable coexistence for 4,200 ticks", "Predators drove prey extinct at tick 1,850, then starved", etc.).
**Visual clarity:**
- Distinct, readable rendering for tree food, cute oval prey, and cute oval predators. You should be able to watch a predator close on prey, a cluster scatter, and an agent pause to eat.
- Show selection/inspection: click an agent to see its energy, age, eating state/cooldown, traits, and stats in a side panel.
- Show selection on the 3D map without breaking rotation: click/tap selects, drag rotates.
</baseline-features>
<stretch-features>
Do as many as you can without breaking the baseline. These are what separate a great submission from a merely correct one:
- **Evolution / genetics**: give agents heritable traits (speed, vision, size, metabolism) that mutate slightly on reproduction. Faster creatures burn more energy; better-sensing creatures find food faster. Over many generations, watch traits drift under selection pressure — and add a chart of average trait values over time so evolution is *visible*. (This is the Primer / natural-selection experience and it is spectacular when it works.)
- Trait-distribution histograms that update live.
- Phase-space (Lotka-Volterra) plot: predators on one axis, prey on the other — a correct sim traces a closed loop/spiral, which is a beautiful, objective proof of correctness.
- Multiple food types or biomes with different regrowth; seasons that modulate food rate over time.
- Sexual reproduction with trait mixing; simple flocking/herding for prey; pack hunting for predators.
- Day/night or weather that changes vision and metabolism.
- Save/load a world (settings + RNG seed + tick) to JSON; export the run's time-series as CSV; export the summary chart as PNG.
- A "family tree" / lineage inspector for a clicked agent.
- Heatmaps of where death, births, or food density concentrate.
- Time-scrubbing: record enough history to rewind and replay the run.
</stretch-features>
<correctness-checks>
Before you consider this done, your simulation should be able to demonstrate — with the right settings — ALL of the following. If it can't, the energy economy is wrong, not the settings:
1. A run where predator and prey populations oscillate out of phase for a long time (predator peaks lag prey peaks).
2. A run where too many predators cause prey extinction, followed by predator starvation and collapse.
3. A run where too little food causes prey to crash even with no predators.
4. Populations that self-regulate around a carrying capacity instead of growing to infinity.
If you built the evolution stretch: a run where average speed (or vision) measurably shifts over generations under a selection pressure.
</correctness-checks>
<constraints>
- Deliver a SINGLE, self-contained `.html` file. No build step, no external libraries, no CDN, no frameworks. Vanilla JS + Canvas. It must run by double-clicking the file, fully offline.
- All rendering (world AND charts) is hand-drawn on canvas — do not pull in a charting library.
- The 3D/rotating map must also be built with vanilla JS + Canvas. Do not depend on Three.js or any external renderer.
- No `any`-style sloppiness even in plain JS: clean structure, no god-function, clear separation between simulation model, rendering, and UI.
- Performance target: 2,000+ agents at 60fps on the balanced preset. Turbo mode should push far past that with rendering throttled.
</constraints>
<important>
* You MUST write the result directly into a file named "index.html" on the user's computer. The user should not have to see or handle the code — just write the file and finish your task.
* Title of the page (the browser tab `<title>`) is your model name. For example "GPT 5" or "Opus 5".
* Show your model name as a heading inside the page too.
</important>