imageUnit 7
Conditional Branching

Unit Overview

Students use geometry and conditional branching to move their player characters in response to key-presses.

Learning Objectives:

  • Students learn the concept of piecewise functions

  • Students learn about conditionals (how to write piecewise functions in code)

  • Students learn that handling user input needs piecewise functions

  • Students learn which questions to ask to detect key presses

  • Students learn how to write their own conditional expressions

  • Students reason about relative positioning of objects using mathematics

Product Outcomes:

  • Students will write update-player, which moves their player in response to key-presses

Standards:

See our Standards Document provided as part of the Bootstrap curriculum.
  • A-SSE.1-2: Interpret the structure of expressions

  • F-IF.1-3: Understand the concept of a function and use function notation

  • F-IF.4-6: Interpret functions that arise in applications in terms of the context

  • F-IF.7-9: Analyze functions using different representations

  • F-LE.5: Interpret expressions for functions in terms of the situation they model

  • A-CED.1-4: Create equations that describe numbers or relationships

  • F-BF.1-2: Build a function that models a relationship between two quantities

Length: 50 minutes

Glossary:

  • clause: a question and its corresponding answer in a conditional expression

  • conditional: a code expression made of questions and answers

  • piecewise function: a function that computes different expressions based on its input

Types

Functions

Number

+ - * / sq sqrt expt

String

string-append string-length

Image

rectangle circle triangle ellipse radial-star scale rotate put-image

Boolean

= > < string=? and or

Luigi’s Pizza

Overview

Students analyze the behavior of a piecewise function

Learning Objectives

  • Students learn the concept of piecewise functions

  • Students learn about conditionals (how to write piecewise functions in code)

Evidence Statements

  • Students will understand that functions can perform different computations based on characteristics of their inputs

  • Students will begin to see how Examples indicate the need for piecewise functions

  • Students will understand that cond statements capture pairs of questions and answers when coding a piecewise function

Product Outcomes

    Standards

    • A-SSE.1-2: Interpret the structure of expressions

    • F-IF.1-3: Understand the concept of a function and use function notation

    • F-IF.4-6: Interpret functions that arise in applications in terms of the context

    • F-IF.7-9: Analyze functions using different representations

    • F-LE.5: Interpret expressions for functions in terms of the situation they model

    Materials

    • Computers w/ DrRacket or WeScheme

    • Student workbook

    • Pens/pencils for the students, fresh whiteboard markers for teachers

    • Class posters (List of rules, basic skills, course calendar)

    • Language Table (see below)

    Preparation

    • "Luigi’s Pizza" [LuigisPizza.rkt from source-files.zip \| WeScheme] preloaded on students’ machines, and on the projector

    Luigi’s Pizza (Time 20 min)

    • Review students’ answers to the exercise.

    • The code for the cost function is written below:

    • Up to now, all of the functions you’ve seen have done the same thing to their inputs:

      • green-triangle always made green triangles, no matter what the size was.

      • safe-left? always compared the input coordinate to -50, no matter what that input was.

      • update-danger always added or subtracted the same amount

      • and so on...

      This was evident when going from EXAMPLEs to the function definition: circling what changes essentially gives away the definition, and the number of variables would always match the number of things in the Domain.

      It may be worthwhile to have some EXAMPLEs and definitions written on the board, so students can see this point illustrated.

    • The cost function is special, because different toppings can result in totally different expressions being evaluated. If you were to circle everything that changes in the example, you would have the toppings circles and the price. That’s two changeable things, but the Domain of the function only has one thing in it!

    • Of course, price isn’t really an independent variable, since the price depends entirely on the topping. For example: if the topping is "cheese" the function will simply produce 9.00, if the topping is "pepperoni" the function will simply produce 10.50, and so on. The price is still defined in terms of the topping, and there are four possible toppings - four possible conditions - that the function needs to care about. The cost function makes use of a special language feature called conditionals, which is abbreviated in the code as cond.

    • Each conditional has at least one clause. Each clause has a Boolean question and a result. In Luigi’s function, there is a clause for cheese, another for pepperoni, and so on. If the question evaluates to true, the expression gets evaluated and returned. If the question is false, the computer will skip to the next clause.

      Look at the cost function:
      • How many clauses are there for the cost function?

      • Identify the question in the first clause.

      • Identify the question in the second clause.

      Square brackets enclose the question and answer for each clause. When students identify the questions, they should find the first expression within the square brackets. There can only be one expression in each answer.

    • The last clause in a conditional can be an else clause, which gets evaluated if all the questions are false.

      In the cost function, what gets returned if all the questions are false? Why is it a good idea to have an else clause?

      Else clauses are best used as a catch-all for cases that you can’t otherwise enumerate. If you can state a precise question for a clause, write the precise question instead of else. For example, if you have a function that does different things depending on whether some variable x is larger than 5, it is better for beginners to write the two questions (> x 5) and (<= x 5) rather than have the second question be else. Explicit questions make it easier to read and maintain programs. When you use else, someone has to read all the previous questions to know what condition else corresponds to: they can’t just skim all the questions to find the one that matches their situation. This might be counterintuitive to those with prior programming experience, but it does help make code more readable and understandable.

    • Functions that use conditions are called piecewise functions, because each condition defines a separate piece of the function.

    • Why are piecewise functions useful? Think about the player in your game: you’d like the player to move one way if you hit the "up" key, and another way if you hit the "down" key. Moving up and moving down need two different expressions! Without cond, you could only write a function that always moves the player up, or always moves it down, but not both.

    Player Movement

    Overview

    Students write a piecewise function that allows their player to move up and down using the arrow keys.

    Learning Objectives

    • Students learn that handling user input needs piecewise functions

    • Students learn which questions to ask to detect key presses

    • Students learn how to write their own conditional expressions

    • Students reason about relative positioning of objects using mathematics

    Evidence Statements

    • Students will understand how to write different expressions that compute new coordinates in different directions

    • Students will be able to write expressions that check which key was pressed

    • Students will be able to write a conditional connecting key presses to different directions of movement

    • Students will learn to write examples that illustrate each condition in a piecewise function

    • Students will be able to experiment with using functions to change the speed or nature of character movement in a game

    Product Outcomes

    • Students will write update-player, which moves their player in response to key-presses

    Standards

    • A-CED.1-4: Create equations that describe numbers or relationships

    • A-SSE.1-2: Interpret the structure of expressions

    • F-BF.1-2: Build a function that models a relationship between two quantities

    • F-IF.1-3: Understand the concept of a function and use function notation

    • F-IF.4-6: Interpret functions that arise in applications in terms of the context

    • F-IF.7-9: Analyze functions using different representations

    • F-LE.5: Interpret expressions for functions in terms of the situation they model

    Materials

    • Student workbook

    • All student computers should have their game templates pre-loaded, with their image files linked in

    Preparation

      Player Movement (Time 25 min)

      • Now that we know cond, we can write update-player.

        image Look at the following picture, which describes what happens when the "up" arrow key is pressed.
        • What is the player’s starting x-coordinate?

        • What is the player’s starting y-coordinate?

        • What about after the player moves?
          • What are the new x and y coordinates?

          • What has changed and by how much?

          • What happens when we press the "down" arrow key?

          • What should the new coordinates be then?

          • What should happen if a user presses a key other than the up or down arrows?

        Draw a screen on the board, and label the coordinates for a player, target and danger. Circle all the data associated with the Player.

      • The following table summarizes what should happen to the player for each key:

        When...

        Do...

        key is "up"

        add 20 to player-y

        key is "down"

        subtract 20 from player-y

        key is anything else

        return y unchanged

      • On Page 26 in your workbook, you’ll find the word problem for update-player.

        Be sure to check students’ Contracts and EXAMPLEs during this exercise, especially when it’s time for them to circle and label what changes between examples. This is the crucial step in the Design Recipe where they should discover the need for cond.

      • If you don’t like using the arrow keys to make the player move up and down, you can just as easily change them to work with "w" and "x".

      • You can also add more advanced movement, by using what you learned about boolean functions. Here are some ideas:

        • Warping: instead of having the player’s y-coordinate change by adding or subtracting, replace it with a Number to have the player suddenly appear at that location. (For example, hitting the "c" key causes the player to warp back to the center of the screen, at y=240.)

        • Boundary-detection Change the condition for moving up so that the player only moves up if key="up" AND player-y is less than 480. Likewise, change the condition for "down" to also check that player-y is greater than 0.

        • Wrapping: Add a condition (before any of the keys) that checks to see if the player’s y-coordinate is above the screen (y > 480). If it is, have the player warp to the bottom (y=0). Add another condition so that the player warps back up to the top of the screen if it moves below the bottom.

        • Challenge: Have the player hide when the "h" key is pressed, only to re-appear when it is pressed again!

        Hint on the challenge: multiply by -1.

      Closing

      Overview

      Learning Objectives

        Product Outcomes

          Standards

            Materials

              Preparation

                Closing (Time 5 min)

                • Congratulations - you’ve got the beginnings of a working game! What’s still missing? Nothing happens when the player collides with the object or target! We’re going to fix these over the next few lessons, and also work on the artwork and story for our games, so stay tuned!

                imageBootstrap by Emmanuel Schanzer is licensed under a Creative Commons 3.0 Unported License. Based on a work at www.BootstrapWorld.org. Permissions beyond the scope of this license may be available at schanzer@BootstrapWorld.org.