bebraw
1/19/2010 - 6:49 PM

agents.py

from random import randint

MARBLE_AMOUNTS = (randint(1, 10), randint(1, 10), randint(1, 10), )
MARBLE_COLORS = ('black', 'white', 'green', )

class Marbles(list):
    # Note that I stored only color of each marble instead of instantiating
    # actual Marble objects. If Marble object would require more data, in
    # that case one should be implemented.

    def append(self, amount, color):
        assert isinstance(amount, int)
        assert isinstance(color, str)

        for i in range(amount):
            super(Marbles, self).append(color)

    def remove(self, color, amount):
        if color == 'all':
            for marble_color in self.colors:
                for i in range(amount):
                    try:
                        super(Marbles, self).remove(marble_color)
                    except ValueError:
                        break

    @property
    def colors(self):
        ret = set()

        for marble in self:
            ret.add(marble)

        return ret

class Table:
    def __init__(self):
        assert len(MARBLE_AMOUNTS) == len(MARBLE_COLORS)

        self.marbles = Marbles()
        
        for amount, color in zip(MARBLE_AMOUNTS, MARBLE_COLORS):
            self.marbles.append(amount, color)

class Environment:
    def __init__(self):
        self.table = Table()
import time
from agents import Agents
from environment import Environment

STEP_INTERVAL = 0.2

class Application:
    def __init__(self):
        self.env = Environment()
        self.agents = Agents(self.env)

    def run(self):
        while True:
            for agent in self.agents:
                print self.env.table.marbles

                ret = agent.act()

                if ret:
                    print 'Result: ' + ret
                    raise SystemExit
                
                time.sleep(STEP_INTERVAL)

if __name__ == '__main__':
    app = Application()
    app.run()
class Agent(object):
    def __init__(self, env):
        self.env = env

class GetColor(Agent):
    def act(self):
        if len(self.env.table.marbles.colors) == 1:
            return self.env.table.marbles[0]

class RemoveMarbles(Agent):
    def act(self):
        self.env.table.marbles.remove('all', 1)

class NoMarblesLeft(Agent):
    def act(self):
        if len(self.env.table.marbles.colors) == 0:
            return 'No marbles left!'

class Agents(list):
    def __init__(self, env):
        # ideally these would be loaded automagically from a given module
        agent_classes = (GetColor, RemoveMarbles, NoMarblesLeft)
        agent_instances = []

        for agent_class in agent_classes:
            agent_instances.append(agent_class(env))
        
        super(Agents, self).__init__(agent_instances)