> For the complete documentation index, see [llms.txt](https://easy-draw.joemazzone.net/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://easy-draw.joemazzone.net/python-curriculum/unit-2-drawing-algorithms.md).

# Unit 2: Drawing Algorithms

In this unit students let the computer do the repetitive work. They use **variables**, **loops**, **conditionals**, **lists**, and the **random** module to draw patterns that would take hundreds of lines to write by hand.

{% hint style="info" %}
**Teacher notes**

* **Time:** 11 class periods: 6 lessons (1 class each) and 5 classes for the unit project
* **Before this unit:** students have finished [Unit 1: Drawing Basics](https://easy-draw.joemazzone.net/python-curriculum/unit-1-drawing-basics.md).
* **Big idea:** an *algorithm* is a step-by-step plan. If students can describe a drawing as steps that repeat, they can code it with a loop.
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Use variables and arithmetic to position shapes relative to each other.
2. Use `for` loops with `range()` to repeat a drawing step.
3. Use nested loops to draw rows and grids.
4. Use `if`, `elif`, and `else` to make decisions inside a loop.
5. Use lists to store colors and points.
6. Use the `random` module to draw something different each time the program runs.

## Lesson 2.1: Variables Make Drawings Move Together

If every shape in a face uses its own numbers, moving the face means changing every number. If every shape is placed **relative** to `x` and `y`, we only change two numbers.

```python
import easy_draw

easy_draw.load_canvas()

x = 300
y = 300
size = 100

head = easy_draw.Circle(center_xy = (x, y), radius = size, color = "gold")
left_eye = easy_draw.Circle(center_xy = (x - size / 3, y - size / 4), radius = size / 8)
right_eye = easy_draw.Circle(center_xy = (x + size / 3, y - size / 4), radius = size / 8)
mouth = easy_draw.Arc(
    center_xy = (x, y + size / 4),
    width = size,
    height = size / 2,
    sweep_angle = 180,
    style = "arc",
    border_width = 5
)

easy_draw.end()
```

**Practice:** Change `x`, `y`, and `size` and run the program. Does the face stay together? Then add a nose that also uses `x`, `y`, and `size`.

## Lesson 2.2: Loops

A `for` loop repeats code. The loop variable changes each time, so we can use it to move each shape.

```python
import easy_draw

easy_draw.load_canvas()

for i in range(10):
    easy_draw.Circle(center_xy = (30 + i * 60, 300), radius = 25, color = "blue")

easy_draw.end()
```

Walk through the first few times the loop runs as a table: when `i` is 0 the x is 30, when `i` is 1 the x is 90, and so on.

The loop variable can change size and color too. Drawing big shapes first keeps the small ones on top:

```python
import easy_draw

easy_draw.load_canvas()

for i in range(10):
    shade = i * 25
    easy_draw.Circle(center_xy = (300, 300), radius = 250 - i * 25, color = (shade, 0, 255 - shade))

easy_draw.end()
```

**Practice:**

1. Draw a staircase of 8 squares.
2. Draw 12 lines that all start at (300, 300) and end at different points along the bottom of the canvas.
3. Draw a "fan" by rotating a long thin rectangle a little more each time through the loop.

## Lesson 2.3: Nested Loops and Grids

A loop inside another loop draws rows and columns.

```python
import easy_draw

easy_draw.load_canvas()

for row in range(8):
    for col in range(8):
        if (row + col) % 2 == 0:
            color = "black"
        else:
            color = "red"
        easy_draw.Rectangle(xy = (col * 75, row * 75), width = 75, height = 75, color = color)

easy_draw.end()
```

**Discussion:** What does `(row + col) % 2 == 0` check? Fill in a small table of `row`, `col`, and `(row + col) % 2` to find out.

**Practice:**

1. Change the checkerboard to 10 x 10. What else has to change?
2. Draw a grid of circles where every circle in the top half is blue and every circle in the bottom half is green.

## Lesson 2.4: Lists

A list can hold the colors for a pattern. `%` (remainder) makes the colors repeat.

```python
import easy_draw

easy_draw.load_canvas()

rainbow = ["red", "orange", "yellow", "green", "blue", "purple"]

for i in range(12):
    easy_draw.Rectangle(xy = (i * 50, 0), width = 50, height = 600, color = rainbow[i % len(rainbow)])

easy_draw.end()
```

A loop can also build a `points_list`. This draws a star by alternating between a far point and a close point around a circle.

```python
import easy_draw
import math

easy_draw.load_canvas(background = "midnightblue")

points = []
for i in range(10):
    angle = math.radians(i * 36 - 90)
    if i % 2 == 0:
        distance = 200
    else:
        distance = 80
    points.append(300 + distance * math.cos(angle))
    points.append(300 + distance * math.sin(angle))

star = easy_draw.Polygon(points_list = points, color = "gold")

easy_draw.end()
```

**Practice:** Change the star to have 8 points. Which numbers have to change?

## Lesson 2.5: Random

The `random` module makes every run different.

```python
import easy_draw
import random

easy_draw.load_canvas(background = "black")

for i in range(200):
    x = random.randint(0, 600)
    y = random.randint(0, 600)
    size = random.randint(1, 4)
    easy_draw.Circle(center_xy = (x, y), radius = size, color = "white")

moon = easy_draw.Circle(center_xy = (480, 120), radius = 60, color = "lightyellow")

easy_draw.end()
```

**Practice:**

1. Make 5% of the stars yellow. (Hint: `if random.randint(1, 100) <= 5:`)
2. Pick each star's color with `random.choice()` from a list of colors.

## Lesson 2.6: Simple Animation

A loop with `time.sleep()` changes a shape a little at a time. The browser shows each change.

```python
import easy_draw
import time

easy_draw.load_canvas()

ball = easy_draw.Circle(center_xy = (50, 300), radius = 30, color = "red")
speed = 10

for step in range(200):
    x = ball.center_xy[0] + speed
    if x > 570 or x < 30:
        speed = -speed
    ball.set_property(center_xy = (x, 300))
    time.sleep(0.02)

easy_draw.end()
```

**Discussion:** What does `speed = -speed` do? What would happen without the `if` statement?

## Unit Project: Generative Art

Students write a program that creates an original piece of art with loops and randomness. Every time the program runs, the art should look a little different, but always in the same style.

Ideas: a city skyline with random building heights, a field of flowers, a quilt pattern, a galaxy, abstract art inspired by a famous artist.

**Requirements:**

* At least one `for` loop and one nested loop.
* At least one `if` statement inside a loop.
* At least one list (of colors, points, or sizes).
* Uses `random` so that each run is different.
* At least 100 shapes drawn, using no more than 60 lines of code.
* Save three different runs with the **Save Canvas** button and turn them in with the code.

| Category       | 4 - Exceeds                                       | 3 - Meets                          | 2 - Approaching                  | 1 - Beginning   |
| -------------- | ------------------------------------------------- | ---------------------------------- | -------------------------------- | --------------- |
| Loops          | Nested loops create a complex, purposeful pattern | A loop and a nested loop are used  | Loops used, but no nested loop   | No loops        |
| Decisions      | Conditionals create several clear effects         | At least one conditional in a loop | Conditional is not inside a loop | No conditionals |
| Lists & random | Lists and random work together in creative ways   | Both a list and random are used    | Only one is used                 | Neither is used |
| Code quality   | Variables for all "magic numbers," clear comments | Clear names and comments           | Few comments                     | Hard to read    |
| Art            | Original, consistent style across runs            | Runs look different but related    | Runs look the same               | Incomplete      |
