Date

Lecture Date: Friday, September 2

Today, we are going to move a bit quick, but mainly so you can see a quick overview of a lot of concepts.

First, you need to get everything setup to go!

  1. Open PyCharm and either make a new project or open an existing one.
  2. Make a new Python file called turtle_drawing.py.
  3. Start by making a new turtle!

Here's some starter code:

import turtle

tom = turtle.Turtle()

tom.forward(50)

turtle.done()

Let's start making this a bit more complex. We'll work up to some of the code below.

# Mark Sherriff (mss2x)

import turtle
import random

def draw_square(t, x, y):
    t.penup()
    t.goto(x,y)
    t.pendown()
    rand_color = random.randint(0,len(colors)-1)
    t.color(colors[rand_color])
    for i in range(4):
        t.forward(100)
        t.left(90)

tom = turtle.Turtle()
tom.speed("fastest")

colors = ["green", "red", "yellow", "orange", "pink", "cyan"]

for i in range(10):
    rand_x = random.randint(-100,100)
    rand_y = random.randint(-100,100)
    draw_square(tom,rand_x,rand_y)

# draw_square(tom)


turtle.done()

Another example:

import turtle
def drawShape(t, sides, size):
    angle = 360.0 / sides
    for i in range(sides):
        if t.color()[0] == "red":
            t.color("black")
        else:
            t.color("red")
        t.forward(size)
        t.left(angle)
dana = turtle.Turtle()
drawShape(dana, 6, 100)
dana.right(180)
drawShape(dana, 5, 100)
turtle.done()

Final code we actually completed today:

import turtle
import random

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

def draw_square(my_turtle, x, y):
   my_turtle.penup()
   my_turtle.goto(x,y)
   my_turtle.pendown()
   for i in range(4):
       rand_color = random.randint(0,len(colors)-1)
       my_turtle.color(colors[rand_color])
       my_turtle.forward(100)
       my_turtle.left(90)

# 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)
   draw_square(yurtle, rand_x,rand_y)

turtle.done()