9. Bringing It Together
Time to see the pieces work as a team! This page builds a tiny creature world that runs in the console (no graphics yet). It uses almost everything from the earlier pages:
- a class for the creatures (8. Classes & Objects)
- a list to hold them all (3. Lists)
- loops to run the world step by step (4. Loops)
- randomness for movement and mutation (5. Randomness)
- if / else for decisions (2. Making Choices)
- f-strings to print nice messages (1. The Basics)
Read it slowly. Try to spot each idea as it appears. Then type it out and run it!
The whole program
Because it uses randomness, you’ll get different results every time you run it — just like a real world.
Let’s walk through it
import randomat the top switches on the random tools.MAX_ENERGY = 100is a constant (CAPITALS) — the top energy any creature can reach.- The
Creatureclass is the blueprint. Each creature has a name, energy, and speed (its properties), and canmove,eat, and checkis_alive(its methods). - We build a list of creatures — our starting population.
- The outer
forloop runs the world 10 times (10 steps). - The inner
forloop gives every creature a turn: it moves, maybe eats, and reports how it’s doing. if random.random() < 0.5:means each creature finds food about half the time.- f-strings turn the numbers into friendly messages.
Now make it yours! (challenges)
The best way to learn is to change things and see what happens. Try these, one at a time:
Add another creature. Put a new
Creature("Nibbles", 3)in the list. Does the loop handle it with no other changes? (It should!)Remove the dead ones. After each step, build a new list of only the creatures that are still alive:
(This is a neat Python shortcut called a list comprehension — it makes a new list, keeping only the items where the
ifis true.)Make babies. If a creature’s energy is very high, give it a baby with a slightly mutated speed, and add the baby to a list of new creatures. (Peek at 5. Randomness for the mutation idea.)
Count the survivors. At the end, print how many creatures are left using
len(creatures).
Take your time. If something breaks, read the error’s bottom line (7. Handling Errors) and fix it. That is programming. 🌱
What’s next?
Right now the world lives in the console as lines of text. In the next page, 10. pygame Basics, we give it a window so you can actually watch your creatures move around on screen.