[Edu-sig] Life Clock

kirby urner kirby.urner at gmail.com
Sat Apr 22 03:48:13 CEST 2006

> This looks like something that could easily adapted to, and better demonstrated
> with Pygame.  Any reason why you aren't doing this?
> André

I want to use pure Python without a lot of extra library stuff.  The
understanding kids develop will rely on the imagination a lot, with
the foreground remaining essentially lexical (just like a science
fiction novel is mostly just words on a page).

You can picture all those little bunnies hopping around in your mind's
eye.  We don't need the overhead of actual graphical bunnies -- though
some puppeting programs may provide them.

Here's some working code except there's something not yet right -- no
fox is eating a bunny yet.  I haven't figured out why.

from random import randint

class Mammal (object):

    def __init__(self, name, eco):
        self.name = name
        self.stomach = []
        self.alive = True
        self.eco = eco
        self.timetolive = 100
        self.clock = 0
        self.xpos = randint(-3,3)
        self.ypos = randint(-3,3)

    def update(self):
        self.clock += 1
        if self.clock > self.timetolive:
            self.alive = False

    def move(self):
        self.xpos += randint(-1, 1)
        self.ypos += randint(-1, 1)

class Bunny (Mammal):

    def iseaten(self, fox):
        self.alive = False
        print '%s is eaten by %s.' % (self, fox)

    def die(self):
        print '%s dies of old age.' % self

    def __repr__(self):
        return 'Bunny %s age: %s @ (%s, %s)' % (self.name, self.clock,
self.xpos, self.ypos)

class Fox (Mammal):

    def eat(self):
        for bunny in self.eco.bunnies.values():
            if (self.xpos == bunny.xpos) and (self.ypos == bunny.ypos):
                self.stomach.append( bunny )

    def die(self):
        print '%s dies of old age.' % self

    def __repr__(self):
        return 'Fox %s age: %s @ (%s, %s)' % (self.name, self.clock,
self.xpos, self.ypos)

class Ecosystem(object):

    def __init__(self):
        self.bunnies = {}
        self.foxes = {}

    def update(self):

        # state change
        for bunny in self.bunnies.values():

        for fox in self.foxes.values():

        # cull
        for i, bunny in self.bunnies.items():
            if not bunny.alive:

        for i, fox in self.foxes.items():
            if not fox.alive:

def main():

    eco = Ecosystem()

    for i in range(100):
        eco.bunnies[i] = Bunny(i, eco)

    for i in range(100):
        eco.foxes[i] = Fox(i, eco)

    print 'Bunnies:', eco.bunnies
    print 'Foxes:  ', eco.foxes

    for cycle in range(200):


More information about the Edu-sig mailing list