The Nature of Code with p5 Python: exercise i.1

Published: 2020-01-16 21:08:46 -0800 -0800

Reading time: 2 mins (254 words)

Tags: p5 p5py thenatureofcode python

Here’s a quick video of my solution:

Here’s the code:

# prompt - create a random walker that has a tendency to move down and to the right

from p5 import *
from random import randint
from typing import Optional

class Walker:
    x: float
    y: float

    def __init__(self, x: float = 0, y: float = 0) -> None:
        self.x = x
        self.y = y

    def move(self, x_offset: float, y_offset: float) -> None:
        self.x += x_offset
        self.y += y_offset

    def display(self) -> None:
        circle((self.x, self.y), 1)

walker: Optional[Walker] = None
should_start: bool = False

def setup():
    global walker

    size(640, 640)

    walker = Walker(width / 2, height / 2)

def draw():
    global walker, should_start

    if should_start:
        walker.move(randint(-1,1) + randint(0, 1), randint(-1,1) + randint(0,1))

def key_pressed():
    global should_start

    if key == " ":
        should_start = True

def main():


A quick explanation of what’s going on:

  • we create a walker class with the ability to store its location, move, and display itself on line 26
  • on 44 we setup our canvas to draw on and create a walker on it
  • on 53 we tell the walker to move and display each time we draw. We accomplish the down and right bias by just adding in another (0, 1) in that direction. Rudimentary to be sure, but it works.
  • then on 66 and 69 we start our program

You can disregard the key_pressed and should_start business on 56 and 60 as those are just to make it easier for me to capture the animations.

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus