Date

Lecture Date: Monday, September 5

We'll keep going with turtle today, finishing up whatever we didn't complete on Friday.

We'll also add some more excitement!

  • random colors
  • user input
  • how to draw a circle
  • how to draw a tree

More complete code for drawing shapes:

# Mark Sherriff (mss2x)

import turtle
import random

yurtle = turtle.Turtle()
yurtle.speed("fastest")
colors = ["green", "red", "yellow", "cyan", "orange", "pink"]

def draw_shape(my_turtle, x, y, num_sides, size):
   my_turtle.penup()
   my_turtle.goto(x,y)
   my_turtle.pendown()
   rand_color = random.randint(0, len(colors) - 1)
   my_turtle.color(colors[rand_color])
   my_turtle.begin_fill()
   for i in range(num_sides):
       my_turtle.forward(size)
       my_turtle.left(360/num_sides)
   my_turtle.end_fill()

# Add code to draw 20 squares on the screen at random locations
for i in range(2000):
   rand_x = random.randint(-300,300)
   rand_y = random.randint(-300,300)
   rand_size = random.randint(10,100)
   rand_sides = random.randint(3,12)
   draw_shape(yurtle, rand_x, rand_y, rand_sides, rand_size)

turtle.done()

Drawing a Tree Fractal:

# Mark Sherriff (mss2x)

import turtle

def draw_tree(t, depth, size):

    if depth == 0:
        return

    if depth == 1:
        t.color("green")
    else:
        t.color("black")
    t.forward(size-depth*2)
    t.left(40)
    t.forward(size-depth*2)
    draw_tree(t, depth-1, size-5)
    if depth == 1:
        t.color("green")
    else:
        t.color("black")
    t.back(size-depth*2)
    t.right(80)
    t.forward(size-depth*2)
    draw_tree(t, depth-1, size-5)
    if depth == 1:
        t.color("green")
    else:
        t.color("black")
    t.back(size-depth*2)
    t.left(40)
    t.back(size-depth*2)



tom = turtle.Turtle()
tom.left(90)
tom.penup()
tom.back(150)
tom.pendown()
tom.speed("fastest")
draw_tree(tom, 5, 20)

turtle.done()

Levy C Curve:

import turtle
import random

colors = ["green", "red", "blue", "yellow"]


def draw_levy(t, level, size):

    if level == 0:
        rand_num = random.randint(0,len(colors)-1)
        t.color(colors[rand_num])
        t.forward(size)
        return

    t.right(45)
    draw_levy(t, level-1, size)
    t.left(90)
    draw_levy(t, level-1, size)
    t.right(45)


tom = turtle.Turtle()
tom.up()
tom.goto(0,0)
tom.down()
tom.speed("fastest")
draw_levy(tom, 10, 5)


turtle.done()