Tuesday, August 16, 2016

Finally Figured Out How to Write a Class for Python Turtles

This explanation/examples did it. Exercise 4.2. Here is what I ended up with.

The code:
 import turtle  
 import random  
 window = turtle.Screen()  
 window.colormode(255)  
 window.bgcolor(0,0,100)  
 border = 150  
 class MyTurtle(turtle.Turtle):  
   def __init__(self):  
     turtle.Turtle.__init__(self, shape="blank")  
   def setup(self):  
     self.width(random.randint(1,3))  
     self.penup()  
     self.setx(random.randint(-border+20,border-20))  
     self.sety(random.randint(-border+20,border-20))  
     self.pendown()  
     self.speed(0)  
     self.pencolor(random.randint(0,255),random.randint(0,255),random.randint(0,255))  
   def move(self):  
     maxStepSize = 40  
     self.circle(random.randint(-maxStepSize,maxStepSize),random.randint(0,270))  
     if self.xcor() < -border:  
       self.penup()  
       self.setx(self.xcor() + maxStepSize)  
       self.pendown()  
     if self.xcor() > border:  
       self.penup()  
       self.setx(self.xcor() - maxStepSize)  
       self.pendown()  
     if self.ycor() > border:  
       self.penup()  
       self.sety(self.ycor() - maxStepSize)  
       self.pendown()  
     if self.ycor() < -border:  
       self.penup()  
       self.sety(self.ycor() + maxStepSize)  
       self.pendown()  
 turtles = ["t1","t2","t3","t4","t5","t6","t7","t8","t9","t10"]  
 for i in range(len(turtles)):  
   turtles[i] = MyTurtle()  
   turtles[i].setup()  
 for i in range(50):  
   for i in range(len(turtles)):  
     turtles[i].move()  
 turtle.done()  

No comments :