P5 Python: The Nature of Code exercise i.3

Date: 2020-03-18 | python | the-nature-of-code | p5 |

Here's a working demo:

Here's the sketch code:

# prompt - create a walker with 50% chance to move in direction of mouse

from p5 import *
from random import randint, random
from typing import Optional
from utils.walker import Walker

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:
        y_move: float = randint(-1, 1)
        x_move: float = randint(-1, 1)

        # find location of mouse
        # increase chance in that direction that we're going there
        should_move_towards_mouse: bool = random() > 0.5

        if should_move_towards_mouse:
            mouse_difference_x: float = mouse_x - walker.x
            mouse_difference_y: float = mouse_y - walker.y

            # find direction
            # make magnitude of 1 and add to walker
            if (y_move < 0) != (mouse_difference_y < 0):
                y_move = change_sign(y_move)

            if (x_move < 0) != (mouse_difference_x < 0):
                x_move = change_sign(x_move)

        walker.move(x_move, y_move)
        walker.display()

def key_pressed():
    global should_start

    if key == " ":
        should_start = True

def change_sign(number: float) -> float:
    return number * -1

def main():
    run()

main()

and a helper Walker class that I built:

from p5 import * 

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)

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.