Dark theme

Classes and objects


Hopefully you've managed to make a single Agent. We'll now set that single agent up. In the __init__ method, make a self.x label, and assign it the value random.randint(0,99). Do the same for the equivalent y variable. You'll need to import random.

We now have our x and y coordinates not only inside our agent, but initialized to a random location and with a proper name that lets us know what they are.

You should now be able to test this works from inside model.py, after your code to make the single agent, by doing this:

a = agentframework.Agent()
print(a.y, a.x)


Next, make a move() method within the Agent class (remember not to make it inside __init__: it needs to be its own method). It doesn't have to take in or return anything. Instead, when called it needs to run the code that we wrote way-back-when, to change the x and y coordinates randomly.

Note that at the moment, this code does this kind of thing inside model.py:

        if random.random() < 0.5:
            agents[i][0] = (agents[i][0] + 1) % 100
        else:
            agents[i][0] = (agents[i][0] - 1) % 100

        if random.random() < 0.5:
            agents[i][1] = (agents[i][1] + 1) % 100
        else:
            agents[i][1] = (agents[i][1] - 1) % 100

Whereas we'll need all the code in the move() method in the Agent class. We'll also need self.x rather than agents[i][1], for example, as we're now inside the class/agent objects, not outside them looking at them in a container. Finally, make sure to leave a copy in model.py for the moment so we don't break anything in there.

Can you copy the code above into a move() method inside your Agent class, and get it working with the new self.x and self.y variables? If you get that working, terrific. We're almost there. You can test it by adding to our model.py:

a = agentframework.Agent()
print(a.y, a.x)
a.move()
print(a.y, a.x)

If you managed that, great, go on, and we'll see about integrating all this into model.py


  1. Building an Agent class
  2. This page
  3. Using the attributes and behaviour <-- next