Drawing Basic Animations in Python

Question:

Hello I am trying to create something like this box with controllable dots
I need to be able to move and interact with the dots. I have tried turtle and pyglet, but neither of them seem to do what I want them to do.

Turtle is letting me create dots but it doesnt seem to play well with oop. I’m a super noob at python oop so maybe I’m just doing it wrong but I can’t seem to make an turtle object that I can actually use how I want. I would ideally be able to use my own methods built off of the turtle methods, and create and call on data unique to each turtle.

import turtle
import time
import random

wn = turtle.Screen()
wn.title("simulation")
wn.bgcolor("tan")
def rng(whatisrandom):
    match whatisrandom:
        case 'coords': return(random.randint(-400,400) , random.randint(-400,400))
        case 'heading':return(random.randint(0,359))
        case 'forward':return(random.randint(0,50))
    
class bug():
    def __init__(self) -> None:
        self = turtle.Turtle(shape = "circle",visible=False)
        self.speed(0)
        self.penup()
        self.setpos(rng('coords'))
        self.showturtle()
        self.speed(1)
        self.forward(20)
        
    def move(self):
        self.setheading(rng('heading'))
        self.forward(rng('forward'))
    
bug1 = bug()
bug1.move()


wn.mainloop()



this is the error message.
self.setheading(rng('heading'))
    ^^^^^^^^^^^^
AttributeError: 'bug' object has no attribute 'heading'

I ultimately want to animate these little bugs with neural nets and train them to do different movements, and eventually interact with each other.

Answers:

This appears to be a misunderstanding of how to subclass an object in Python. Let’s rearrange things a bit:

from turtle import Screen, Turtle
from random import randint

class Bug(Turtle):
    def __init__(self):
        super().__init__(shape='circle', visible=False)

        self.speed('fastest')
        self.penup()
        self.setposition(Bug.rng('coords'))
        self.showturtle()
        self.speed('slowest')
        self.forward(20)

    def move(self):
        self.setheading(Bug.rng('heading'))
        self.forward(Bug.rng('forward'))

    @staticmethod
    def rng(whatisrandom):
        if whatisrandom == 'coords':
            return randint(-400, 400), randint(-400, 400)

        if whatisrandom == 'heading':
            return randint(0, 359)

        if whatisrandom == 'forward':
            return randint(0, 50)

        return None

screen = Screen()
screen.title("Simulation")
screen.bgcolor('tan')

bug1 = Bug()
bug1.move()

screen.mainloop()

I don’t have an issue with your match statement, I’m just unfamiliar with it and haven’t updated my Python sufficiently!

Answered By: cdlane