> 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/java-curriculum/unit-2-if-statements-and-drawings.md).

# Unit 2: If Statements and Drawings

In this unit students make drawings that **make decisions**. Boolean expressions and `if` statements decide what to draw, and event handlers make the decisions happen when the user clicks or presses a key.

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

* **Time:** 10 class periods: 5 lessons (1 class each) and 5 classes for the unit project
* **AP Computer Science A:** Boolean Expressions and if Statements (relational and logical operators, `if`/`else if`/`else`, comparing objects and `String`s with `.equals()`).
* **Before this unit:** students have finished [Unit 1: Using Easy Draw Objects](/java-curriculum/unit-1-using-easy-draw-objects.md).
* Event handlers are written as lambdas. Students only need the pattern `event -> { ... }`; the full idea of lambdas is not needed yet.
  {% endhint %}

## Learning Objectives

Students will be able to:

1. Write boolean expressions with relational operators (`<`, `>`, `<=`, `>=`, `==`, `!=`) and logical operators (`&&`, `||`, `!`).
2. Use `if`, `if`/`else`, and `if`/`else if`/`else` to decide what to draw.
3. Compare `String` values with `.equals()` instead of `==`.
4. Write event handlers that use conditionals to respond to clicks and key presses.
5. Use `static` variables to remember information between events.

## Lesson 2.1: Drawing with Decisions

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        int hour = (int) (Math.random() * 24);

        if (hour >= 6 && hour < 18) {
            EasyDraw.setCanvasColor("skyblue");
            EasyDraw.Circle sun = new EasyDraw.Circle(500, 100, 60);
            sun.setColor("yellow");
        } else {
            EasyDraw.setCanvasColor("midnightblue");
            EasyDraw.Circle moon = new EasyDraw.Circle(500, 100, 50);
            moon.setColor("lightyellow");
        }

        EasyDraw.Text clock = new EasyDraw.Text(300, 550, "Hour: " + hour);
        clock.setSize(32);

        EasyDraw.end();
    }
}
```

**Practice:**

1. Add an `else if` so the sky is `"orange"` at sunset (hours 18 and 19).
2. Draw stars only at night.

## Lesson 2.2: Click Events

An **event handler** is code that runs when something happens, like a click. The code goes inside `event -> { ... }`.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Circle light = new EasyDraw.Circle(300, 300, 100);
        light.setColor("gray");

        light.eventSetup("<Button-1>", event -> {
            if (light.getColor().equals("gray")) {
                light.setColor("yellow");
            } else {
                light.setColor("gray");
            }
        });

        EasyDraw.end();
    }
}
```

**Discussion:** Why do we use `light.getColor().equals("gray")` and not `light.getColor() == "gray"`? (`==` checks whether two references point to the same object. `.equals()` checks whether two strings have the same characters.)

## Lesson 2.3: Remembering with Static Variables

A lambda cannot change a local variable from `main`. A `static` variable of the class can be changed, so it can remember information between clicks.

```java
public class Main {
    static int state = 0;

    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Rectangle box = new EasyDraw.Rectangle(250, 100, 100, 300);
        box.setColor("black");
        EasyDraw.Circle light = new EasyDraw.Circle(300, 250, 40);
        light.setColor("red");

        box.eventSetup("<Button-1>", event -> {
            state = state + 1;
            if (state > 2) {
                state = 0;
            }

            if (state == 0) {
                light.setColor("red");
                light.setCenter(300, 150);
            } else if (state == 1) {
                light.setColor("green");
                light.setCenter(300, 350);
            } else {
                light.setColor("yellow");
                light.setCenter(300, 250);
            }
        });

        EasyDraw.end();
    }
}
```

**Practice:** Add a `Text` object that shows `"STOP"`, `"GO"`, or `"SLOW"`.

## Lesson 2.4: Where Was the Click?

The `event` has the mouse position in `event.x` and `event.y`. Conditionals can check which part of the canvas was clicked.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Line divider = new EasyDraw.Line(300, 0, 300, 600);
        EasyDraw.Text message = new EasyDraw.Text(300, 300, "Click anywhere");
        message.setSize(28);

        EasyDraw.canvasEventSetup("<Button-1>", event -> {
            if (event.x < 300 && event.y < 300) {
                message.setText("Top left");
            } else if (event.x >= 300 && event.y < 300) {
                message.setText("Top right");
            } else if (event.x < 300) {
                message.setText("Bottom left");
            } else {
                message.setText("Bottom right");
            }
        });

        EasyDraw.end();
    }
}
```

**Practice:** Add a horizontal line so the four parts are easy to see. Then change the background color to match the part that was clicked.

## Lesson 2.5: Keyboard Events and Boundaries

Keys move a player. Conditionals keep the player on the canvas.

```java
public class Main {
    public static void main(String[] args) {
        EasyDraw.loadCanvas();

        EasyDraw.Circle player = new EasyDraw.Circle(300, 300, 25);
        player.setColor("blue");

        EasyDraw.canvasEventSetup("<Key>", event -> {
            double x = player.getCenterX();
            double y = player.getCenterY();

            if (event.keysym.equals("Left") && x > 25) {
                x = x - 20;
            } else if (event.keysym.equals("Right") && x < 575) {
                x = x + 20;
            } else if (event.keysym.equals("Up") && y > 25) {
                y = y - 20;
            } else if (event.keysym.equals("Down") && y < 575) {
                y = y + 20;
            }

            player.setCenter(x, y);
        });

        EasyDraw.end();
    }
}
```

{% hint style="info" %}
Key presses only reach Easy Draw when the Easy Draw page is the active browser tab. Click the page first.
{% endhint %}

**Practice:**

1. Turn the player red when it is in the right half of the canvas and blue in the left half.
2. Draw a goal square. When the player is inside it, show `"You win!"`. (Hint: use `&&` to check both x and y.)

## Unit Project: Choose Your Path

Students build an interactive drawing that changes based on what the user does. Ideas:

* **Mood Ring** - clicking different parts of a face changes its expression and color.
* **Quiz Show** - a question with clickable answer boxes that say "Correct!" or "Try again."
* **Maze Escape** - arrow keys move a player who cannot leave the path and wins at the exit.
* **Weather Station** - keys pick the weather and the scene changes to match.

**Requirements:**

* At least one `if`/`else if`/`else` chain.
* At least one compound boolean expression with `&&` or `||`.
* At least one `String` comparison with `.equals()`.
* At least two event handlers, with at least one using `event.x`/`event.y` or `event.keysym`.
* At least one `static` variable that remembers information between events.

| Category     | 4 - Exceeds                                        | 3 - Meets                                      | 2 - Approaching              | 1 - Beginning      |
| ------------ | -------------------------------------------------- | ---------------------------------------------- | ---------------------------- | ------------------ |
| Conditionals | Nested and chained conditionals used purposefully  | `if`/`else if`/`else` and compound expressions | Only simple `if` statements  | No conditionals    |
| Events       | 3+ handlers that work smoothly together            | 2+ handlers using event information            | 1 handler                    | Events do not work |
| State        | Several static variables track the program's state | A static variable remembers information        | State is attempted but buggy | No state           |
| Code quality | Clear names, comments, and organization            | Comments explain each handler                  | Few comments                 | Hard to read       |
| Design       | Creative, polished, with clear instructions        | Works and is easy to use                       | Partly works                 | Does not work      |
