Lesson 24: Functions

Overview

Question of the Day: How can programmers use functions to create their own abstractions?

Students learn how to create functions to organize their code, make it more readable, and remove repeated blocks of code. Students first think about what sorts of new blocks they would like in Game Lab, and what code those blocks would contain inside. Afterwards students learn to create functions in Game Lab. They will use functions to remove long blocks of code from their draw loop and to replace repeated pieces of code with a single function.

Purpose

In previous lessons students have learned to use a number of abstractions in their programs, including the velocity properties, isTouching, and collisions. These abstractions have allowed them to build much more complex programs while ignoring the details of how that behavior is created. In this lesson students learn to build abstractions of their own by creating functions.

Students will primarily use functions to break code into logical chunks that are easier to reason about. This foreshadows the chapter's transition from building technical skill to the organizational processes used to develop software.

Assessment Opportunities

  1. Create and use functions for blocks of code that perform a single high-level task within a program

    See Level 10 in Code Studio.

  2. Explain the advantages of using functions in a program.

    In the wrap up discussion, make sure students understand that functions can increase both the readability and organization of code.

  3. Explain how functions allow programmers to reason about a program at a higher level

    In the wrap up, students should make the connection between functions and abstraction, that functions allow a programmer to name a bit of code so that they can think about it at that higher level, rather than worry about all the details.

Agenda

Lesson Modifications

Warm Up (5 min)

Activity (30 min)

Wrap Up (10 min)

View on Code Studio

Objectives

Students will be able to:

  • Create and use functions for blocks of code that perform a single high-level task within a program
  • Explain the advantages of using functions in a program
  • Explain how functions allow programmers to reason about a program at a higher level

Links

Heads Up! Please make a copy of any documents you plan to share with students.

For the Teachers

Vocabulary

  • Function - A named bit of programming instructions.

Introduced Code

Support

Report a Bug

Teaching Guide

Lesson Modifications

Attention, teachers! If you are teaching virtually or in a socially-distanced classroom, please see these modifications for Unit 3.

Warm Up (5 min)

Your Personal Blocks

Discussion Goal

As students share their ideas, make sure they have a clear idea of the code that they would use to make the block, reminding them that all of the blocks they have learned this chapter (e.g. velocity, collisions) have been built from blocks that they already knew.

Prompt: What's one block you'd like to have in Game Lab? What would it do? What code would it use to work?

Think-Pair-Share: Allow students to explain their blocks to a partner before sharing out their ideas.

Remarks

Today, we're going to learn how to create our own blocks so that we decide exactly how they will work. These special blocks are called functions, and they are one of the most powerful parts of programming.

Question of the Day: How can programmers use functions to create their own abstractions?

Activity (30 min)

Transition: Move students into Code Studio where they will learn to create and call functions.

Wrap Up (10 min)

Assessment Opportunity

Goal: Use this first prompt to review what students learned today. When they create a function they are creating their own block that they can call or use whenever they like. They saw at least two primary motivations for creating functions today including:

  • Simplifying code by breaking it into logically named chunks
  • Allowing a programmer to think at a higher level by hiding the details or a particular bit of programming instructions
  • Avoiding repeated code by making one block you can use multiple times

Students should review the definition of abstraction as "a simple way of representing something complex". Note that a function is an abstraction because it allows you to create one simple name for a more complex block of code.

Key Vocabulary:

  • Function - a named bit of programming instructions

Prompt: Why would we say that functions allow us to "create our own blocks?" Why is this something we'd want to do? Why would a function count as an abstraction?

Discuss: Have students discuss at their table before talking as a class.

Remarks

Functions are a useful tool for helping us write and organize more complex pieces of code. As we start looking to the end of the unit and your final project, being able to keep your code organized will be an important skill.

Question of the Day: How can programmers use functions to create their own abstractions?

  • Lesson Overview
  • 1
  • (click tabs to see student view)
View on Code Studio

Student Instructions

  • Video: Functions
  • 2
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Discussion Goals

Key Vocabulary:

  • Function - a named bit of programming instructions

Make sure students understand role of the two steps in using functions, as well as seeing functions as a form of "chunking" or abstraction. The function definition should include all of the code that they want to run, and the name of the function should be a short description of the purpose of the code. The function should be called at each place in the program that the student wants that block of code to run.

Student Instructions

Questions to Consider

  • Think of a time when a function might have helped you write a program.
  • What code would go in the definition of the function?
  • When would you call the function?
  • What would you name it?
  • Skill Building
  • 3
  • 4
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Introducing Functions

In these first several lessons students are just being shown the syntax of functions and are not asked to write or create their own. It can be useful to explain creating a function as basically “creating a new block” just like another programmer created the “isTouching” or “velocity” blocks that they’ve seen actually contain other more complex code.

Student Instructions

Calling Functions

Functions let you build your own blocks and decide what code goes inside of them. This program has already created two functions, but only one of them is being called.

Do This

  • Call the second function to reveal the full image. Use the function that is being called as a guide.
  • Tip: Just as with all other blocks, spelling and capitalization are important here.
View on Code Studio

Student Instructions

Reordering Code

Placing code inside functions makes it easy to read and make changes to. Good names for functions indicate what your program is doing to a reader. You can call your functions in a different order to quickly make significant changes to how your program runs.

Do This

This program has already created 4 functions that draw parts of a scene. Unfortunately it's not coming out right.

  • Read the 4 functions to know what they do
  • Call the functions in an order that draws the scene in the way that looks best to you
  • Predict
  • 5
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Does It Matter Where You Create Functions?

So far all your functions have been created at the bottom of your code. What do you think will happen if you call a function before it's defined?

Notice that the red square is drawn before its function is created while the green square is drawn after its function is created. Which of these do you think will be drawn?

The red square will be drawn but the green one will not. You cannot call functions after they are created.

The green square will be drawn but the red one will not You cannot call functions before they are created.

Both squares will be drawn. You can create functions anywhere you like in your code.

Neither square will be drawn. There is an error in the code.

View on Code Studio

Student Instructions

Practice using functions and learn more about what makes them so useful.


Choose from the following activities:
a
Calling Functions in the Draw Loop

Call the function to draw the background in the draw loop.

b
Calling Functions Multiple Times

Make the flyer reappear on the right side when it goes off the left.

c
Making Changes to Functions

Change the setFlyer() function so that the flyer appears at a random y with random velocity.

d
Creating Functions to Organize Code

Add code to the drawNight() function to create a night scene.

View on Code Studio

Student Instructions

Calling Functions in the Draw Loop

You can call a function inside the draw loop, just as you would anywhere else in your code.

Do This

A function that will draw a background has been created for you. A sprite has been created to move across the background.

  • Call the function inside the draw loop so that the sprite appears on top of the background.
  • Note: Don't create functions inside the draw loop. Make them at the bottom of your code.
View on Code Studio

Teaching Tip

Why Use Functions

This and the next two levels introduce three uses of functions, namely removing repetition in programs, allowing code to quickly be changed at multiple points, and providing organization in code. Students will need to write more of their own functions in these levels.

Student Instructions

Calling Functions Multiple Times

You'll often want to use the same code at many places in your program. Once you've created a function you can call it as many times as you like.

Do This

This code creates a sprite that moves across the screen once. How can you make it go back across the screen?

  • Note: The function is already called once at the beginning of your program
  • Read the condition of the if-statement inside the draw loop. Why do you think it's there?
  • Use this if-statement and the function written for you to make the sprite move across the screen multiple times.
View on Code Studio

Student Instructions

Making Changes to Functions

A nice benefit of using functions to remove repeated code is that you can now easily make changes to multiple places in your code. Just change how you create the functions, and your program will now use the new code everywhere your function is called.

Do This

Make changes to the setFlyer function so that the flyer starts at a random Y location between 0 and 400, and moves at a random velocity every time it is reset.

View on Code Studio

Student Instructions

Creating Functions to Organize Code

In Game Lab all the action is happening in the draw loop, but too much complex code makes it really confusing to read. To keep your draw loop easy to read, use functions for larger chunks of code. You can call them inside the draw loop and define them below. This is a really good example of using abstraction to think about problems at a high level and worry about details later.

Do This

This program should draw a daytime scene or a nighttime scene, depending on the location of the mouse. The draw loop describes what needs to happen but one of the functions hasn't been written yet.

  • Write the drawNight function which has been created but is empty.
  • Hint: Look at the picture to the right for how your night image should look. Can you use the drawDay function to help you at all?
  • Quick Check
  • 7
  • (click tabs to see student view)
View on Code Studio

Student Instructions

Using Functions

What are three ways that functions can be useful when you are writing programs?

Hint: Go back to the practice levels for review if you are not sure.

  • Collector Game
  • 8
  • 9
  • 10
  • (click tabs to see student view)
View on Code Studio

Teaching Tip

Functions in Context

In this and the next two lessons, students will use functions to organize code within a simple game. While it is not identical to the side scroller, many of the skills and uses of functions in these levels can and should be used when they complete their side scroller.

Student Instructions

Write Your Own Function

Time to practice writing functions of your own. This is a very simple game in which coins fall from the sky and the bunny tries to catch them. All you need to do is write the function that sets up the coin.

Do This

  • Read and run the code that already exists to make sure you know how it works.
  • Write the code for the setCoin function to do the following:
  • Set the coin's velocity to move down.
  • Set the coin's y position to the top of the screen
  • Randomize the coin's x position
  • You can go look at some of the previous levels if you need help.
View on Code Studio

Student Instructions

Catch the Coin, Increase the Score

Let's make that score change now, too, to complete the game. You'll need to be able to tell when the bunny is touching the coin and then reset it.

Do This

  • Use an if-statement and the isTouching block to increase the score when the bunny catches the coin.
  • Make sure you're calling your function to reset the coin once it's been caught.
  • Play the game and randomize the velocity of the coin to a range that you think is fun.
View on Code Studio

Assessment Opportunities

Key Concepts:

Define and call functions to organize code and make it easier to reuse.

Assessment Criteria:
Extensive Evidence

The two functions are defined and called within the if statement as instructed, so that different backgrounds display according to the current score. Code is correctly organized inside and outside the draw loop, and there are no extra blocks.

Convincing Evidence

At least one new background function is defined and called successfully inside the program, but may not work exactly as instructed. Code is correctly organized inside and outside the draw loop.

Limited Evidence

A function is both defined and called inside the program, but there may be major errors that prevent it from running successfully, or code has been incorrectly placed in the draw loop.

No Evidence

There are no new functions in the program.

Student Instructions

Change the Background with the Score

Once you've caught 10 coins it's time to celebrate. You should change the background to be something fun.

Do This

  • Use an if-statement and two separate functions to draw your backgrounds.
  • Then go write your functions outside your draw loop. You get to decide what a "simple" or "silly" background are. Have fun with it!
View on Code Studio

Student Instructions

Improve your game and try out these challenges with functions.


Choose from the following activities:
a
Creating Functions to Draw Scenes

Create two functions to draw two different scenes

b
Free Play

None

View on Code Studio

Student Instructions

Creating Functions to Draw Scenes

The provided code draws one of two different scenes based on where the mouse is on the screen. It either calls the drawScene1() function or the drawScene2() function. However, these functions don't exist yet!

Feel free to be creative and draw whatever two scenes you want

Do This

  • Create the drawScene1 and drawScene2 functions
  • Fill them in with code to draw two different scenes
View on Code Studio

Student Instructions

Free Play

Use what you've learned to create whatever you like. When you're finished, you can click to send your creation to a friend, or to send it to your Projects Gallery.

Standards Alignment

View full course alignment

CSTA K-12 Computer Science Standards (2017)

AP - Algorithms & Programming
  • 2-AP-11 - Create clearly named variables that represent different data types and perform operations on their values.
  • 2-AP-12 - Design and iteratively develop programs that combine control structures, including nested loops and compound conditionals.
  • 2-AP-13 - Decompose problems and subproblems into parts to facilitate the design, implementation, and review of programs.
  • 2-AP-14 - Create procedures with parameters to organize code and make it easier to reuse.
  • 2-AP-16 - Incorporate existing code, media, and libraries into original programs, and give attribution.
  • 2-AP-17 - Systematically test and refine programs using a range of test cases.
  • 2-AP-19 - Document programs in order to make them easier to follow, test, and debug.