> 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-3-functions-and-events.md).

# Unit 3: Functions and Events

In this unit students write their own **functions** and use **event handlers** to make drawings that respond to the mouse and keyboard. The unit ends with students building a small game.

{% 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 2: Drawing Algorithms](https://easy-draw.joemazzone.net/python-curriculum/unit-2-drawing-algorithms.md).
* **Keyboard events** only reach the program when the Easy Draw page is the active browser tab. Remind students to click on the page before pressing keys.
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Define functions with parameters to draw reusable pictures.
2. Return an object from a function and use it later.
3. Write event handler functions and bind them with `.event_setup()` and `canvas_event_setup()`.
4. Use the `event` object's `x`, `y`, and `keysym` information.
5. Use `global` variables to keep track of game information like a score.
6. Use the distance formula to check whether two shapes touch.

## Lesson 3.1: Functions That Draw

In Unit 2 students drew a face with `x`, `y`, and `size` variables. Turning that code into a function means we can draw as many faces as we want.

```python
import easy_draw

def draw_tree(x, y, size):
    trunk = easy_draw.Rectangle(
        xy = (x - size / 8, y),
        width = size / 4,
        height = size / 2,
        color = "saddlebrown"
    )
    leaves = easy_draw.Circle(center_xy = (x, y - size / 4), radius = size / 2, color = "forestgreen")

easy_draw.load_canvas(background = "lightblue")

draw_tree(100, 400, 120)
draw_tree(300, 350, 200)
draw_tree(500, 420, 80)

easy_draw.end()
```

Point out that the function must be **defined** before it is **called**, and that `x`, `y`, and `size` are **parameters** that get their values from the **arguments** in each call.

**Practice:**

1. Write `draw_house(x, y)` and draw a street of 4 houses with a loop.
2. Add a `color` parameter to `draw_tree()` so each tree can have a different color.

## Lesson 3.2: Functions That Return Objects

A function can `return` the object it made so the program can change it later.

```python
import easy_draw

def make_button(x, y, label):
    box = easy_draw.Rectangle(xy = (x - 75, y - 25), width = 150, height = 50, color = "steelblue")
    easy_draw.Text(center_xy = (x, y), text = label, color = "white", size = 20)
    return box

easy_draw.load_canvas()

start = make_button(300, 250, "Start")
quit_button = make_button(300, 350, "Quit")

start.set_property(color = "seagreen")

easy_draw.end()
```

## Lesson 3.3: Click Events

An **event** is something the user does, like clicking. An **event handler** is a function that runs when the event happens. Every event handler has an `event` parameter.

```python
import easy_draw
import random

easy_draw.load_canvas()

square = easy_draw.Rectangle(xy = (200, 200), width = 200, height = 200, color = "purple")

def click_square(event):
    square.set_property(color = random.choice(["red", "orange", "green", "blue"]))
    square.rotate(15)

square.event_setup("<Button-1>", click_square)

easy_draw.end()
```

Common mistake: `square.event_setup("<Button-1>", click_square())` with parentheses calls the function right away. We want to give Easy Draw the function's **name** so it can call it later.

**Practice:**

1. Make a circle that grows by 10 every time it is clicked.
2. Make a "light switch": clicking a rectangle changes the background between `"black"` and `"white"` with `easy_draw.set_canvas_color()`.

## Lesson 3.4: Using the Event's Information

Bind an event to the whole canvas with `canvas_event_setup()`. The `event` object tells us where the mouse was.

```python
import easy_draw
import random

easy_draw.load_canvas()

def place_dot(event):
    color = random.choice(["red", "orange", "gold", "green", "blue", "purple"])
    easy_draw.Circle(center_xy = (event.x, event.y), radius = 15, color = color)

easy_draw.canvas_event_setup("<Button-1>", place_dot)
easy_draw.canvas_event_setup("<B1-Motion>", place_dot)

easy_draw.end()
```

Now students have a paint program! `<B1-Motion>` runs while the mouse moves with the button held down.

**Practice:** Press `c` to change the brush color. (Hint: use a global `brush_color` variable and bind `"c"` with `canvas_event_setup()`.)

## Lesson 3.5: Keyboard Events and Global Variables

Arrow keys can move a player. A **global** variable keeps the score between events.

```python
import easy_draw

easy_draw.load_canvas()

player = easy_draw.Circle(center_xy = (300, 300), radius = 25, color = "blue")
score_text = easy_draw.Text(center_xy = (300, 30), text = "Moves: 0", size = 24)
moves = 0

def move(event):
    global moves
    x, y = player.center_xy
    if event.keysym == "Up" and y > 25:
        y = y - 20
    elif event.keysym == "Down" and y < 575:
        y = y + 20
    elif event.keysym == "Left" and x > 25:
        x = x - 20
    elif event.keysym == "Right" and x < 575:
        x = x + 20
    player.set_property(center_xy = (x, y))
    moves = moves + 1
    score_text.set_property(text = "Moves: " + str(moves))

easy_draw.canvas_event_setup("<Key>", move)

easy_draw.end()
```

**Discussion:**

* Why does `move()` need `global moves`, but not `global player`? (Changing a property of an object is not the same as assigning a new value to the variable.)
* What do the `y > 25` and `x < 575` checks do?

## Lesson 3.6: Collisions

Two circles touch when the distance between their centers is less than the sum of their radii.

```python
import math

def touching(circle1, circle2):
    distance = math.dist(circle1.center_xy, circle2.center_xy)
    return distance < circle1.radius + circle2.radius
```

Add a coin to the Lesson 3.5 program. After each move, check `touching(player, coin)`. If they touch, add to the score and move the coin to a random spot.

## Unit Project: Build a Game

Students design and build a small game. Ideas:

* **Click the Target** - a target jumps to a random spot each time it is clicked. Missed clicks on the canvas cost points.
* **Coin Collector** - move with the arrow keys and collect coins while avoiding enemies.
* **Whack-a-Mole** - holes are drawn with a function and a loop. Clicking a mole scores a point.
* **Dress Up / Builder** - click buttons to change the colors and parts of a character.

**Requirements:**

* At least two functions you wrote that draw something, with parameters.
* At least one function that returns an object.
* At least two different kinds of events (for example, clicks and keys).
* Uses the `event` object's information (`x`, `y`, or `keysym`).
* Keeps track of the game with at least one global variable, shown on the screen with a `Text` object.
* Has a way to win, lose, or finish.

| Category     | 4 - Exceeds                                            | 3 - Meets                                    | 2 - Approaching                    | 1 - Beginning  |
| ------------ | ------------------------------------------------------ | -------------------------------------------- | ---------------------------------- | -------------- |
| Functions    | Several well-named functions with parameters & returns | 2+ drawing functions and 1 returns an object | Functions without parameters       | No functions   |
| Events       | 3+ kinds of events that feel smooth to play            | 2 kinds of events, using event information   | 1 kind of event                    | No events work |
| Game state   | Score, levels, or timer all update correctly           | Score is tracked and displayed               | Score is tracked but not displayed | No game state  |
| Code quality | Clear structure, names, and comments                   | Comments explain each function               | Few comments                       | Hard to read   |
| Gameplay     | Fun, polished, has clear instructions                  | Playable with a clear goal                   | Partly playable                    | Not playable   |

{% hint style="success" %}
Have students play each other's games and give feedback before the final version is due.
{% endhint %}
