Essay - Published: 2020.01.17 | p5 | p5py | python | thenatureofcode |
DISCLOSURE: If you buy through affiliate links, I may earn a small commission. (disclosures)
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)
stroke(Color("#be403b"))
background(204)
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))
walker.display()
def key_pressed():
global should_start
if key == " ":
should_start = True
def main():
run()
main()
A quick explanation of what's going on:
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.
The best way to support my work is to like / comment / share for the algorithm and subscribe for future updates.