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:

Read it slowly. Try to spot each idea as it appears. Then type it out and run it!


The whole program

import random

# ---- a constant: the biggest energy any creature can have ----
MAX_ENERGY = 100


class Creature:
    def __init__(self, name, speed):
        self.name = name
        self.energy = MAX_ENERGY
        self.speed = speed

    def move(self):
        # moving costs energy — faster creatures use more
        self.energy -= self.speed

    def eat(self):
        # find a bit of food and gain energy, but never go over the maximum
        food = random.randint(5, 15)
        self.energy += food
        if self.energy > MAX_ENERGY:
            self.energy = MAX_ENERGY

    def is_alive(self):
        return self.energy > 0


# ---- create a starting population ----
creatures = [
    Creature("Spike", 4),
    Creature("Bramble", 2),
    Creature("Pip", 6),
]

# ---- run the world for 10 steps ----
for step_number in range(10):
    print(f"--- Step {step_number} ---")

    for creature in creatures:
        creature.move()

        # sometimes the creature finds food (about half the time)
        if random.random() < 0.5:
            creature.eat()

        # report how this creature is doing
        if creature.is_alive():
            print(f"{creature.name} has {creature.energy} energy.")
        else:
            print(f"{creature.name} has run out of energy!")

print("The simulation has finished.")

Because it uses randomness, you’ll get different results every time you run it — just like a real world.


Let’s walk through it

  1. import random at the top switches on the random tools.
  2. MAX_ENERGY = 100 is a constant (CAPITALS) — the top energy any creature can reach.
  3. The Creature class is the blueprint. Each creature has a name, energy, and speed (its properties), and can move, eat, and check is_alive (its methods).
  4. We build a list of creatures — our starting population.
  5. The outer for loop runs the world 10 times (10 steps).
  6. The inner for loop gives every creature a turn: it moves, maybe eats, and reports how it’s doing.
  7. if random.random() < 0.5: means each creature finds food about half the time.
  8. 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:

  1. Add another creature. Put a new Creature("Nibbles", 3) in the list. Does the loop handle it with no other changes? (It should!)

  2. Remove the dead ones. After each step, build a new list of only the creatures that are still alive:

    creatures = [creature for creature in creatures if creature.is_alive()]

    (This is a neat Python shortcut called a list comprehension — it makes a new list, keeping only the items where the if is true.)

  3. 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.)

  4. 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.