Course E - Functions 1 - A Simple Function for a Superhero

This lesson introduces the concept of functions.

  • Computer science
  • functions
Print lesson
  • Ages 9+
  • 65+ mins
  • JavaScript Blocks

Introduction

This lesson introduces the concept of functions. Functions are pieces of instructions or code that we know we will reuse. Instead of copying and pasting we use functions. We name our block of code and then any time we want to call the code we simply call the function by its name.

In this lesson, we will call a simple function and utilize the buttons to create actions a superhero might do.

Any time you want to repeat code, loops and functions should be considered. There are several benefits to using functions.

First, functions help us when we want to repeat code in many different places throughout our application. We only need to write it once and then call it by name. This benefit will be demonstrated more thoroughly in the second lesson of this series, 'FUNCTIONS FOR A DIGITAL PET'.

Because we are not repeating code so much, functions allow us to write code, which is smaller in size and easier to read. Also, making changes is easier.

Use the following example to highlight how much easier making changes with functions can be.


let KilometersRan = 0
input.onButtonPressed(Button.A, () => {
    Run_FasterThan_A_Speeding_Bullet()
    Run_FasterThan_A_Speeding_Bullet()
    Run_FasterThan_A_Speeding_Bullet()
    Run_FasterThan_A_Speeding_Bullet()
    Run_FasterThan_A_Speeding_Bullet()
})
input.onButtonPressed(Button.B, () => {
    KilometersRan = 5
    basic.showNumber(KilometersRan)
    basic.clearScreen()
    basic.pause(100)
    KilometersRan = 5
    basic.showNumber(KilometersRan)
    basic.clearScreen()
    basic.pause(100)
    KilometersRan = 5
    basic.showNumber(KilometersRan)
    basic.clearScreen()
    basic.pause(100)
    KilometersRan = 5
    basic.showNumber(KilometersRan)
    basic.clearScreen()
    basic.pause(100)
    KilometersRan = 5
    basic.showNumber(KilometersRan)
    basic.clearScreen()
    basic.pause(100)
})
function Run_FasterThan_A_Speeding_Bullet()  {
    KilometersRan = 5
    basic.showNumber(KilometersRan)
    basic.clearScreen()
    basic.pause(100)
}

Here the two buttons do exactly the same thing. If you press A or B they will will both show a blinking 5. Tell students to show a blinking 3 instead. How many changes do we need to make for button A?(1 change) How many changes do we need to make for button B?(5 changes!) Changing the function was much easier than the big block of code.

In our case the functions for our superhero help us accomplish another important benefit functions provide. Functions allow us to organize our code in meaningful ways that connect to the real life projects we program for. In this lesson, you will notice we are able to divide our code into actions our superhero might make. This makes it easier to think about the problem we want to solve and visualize the code working.

Instructors may consider doing the following with this first lesson on functions.

  1. Focus on demonstrating at first. The students mostly watch and listen. (Initial code explanation / Challenge 1)
  2. The teacher continues to do most of the lesson while the student helps. Teacher gives immediate feedback on the help. (Challenge 2 - Independent Practice)

For lesson two, 'FUNCTIONS FOR A DIGITAL PET', instructors can then either repeat the above or move on slowly allowing more responsibility to learners.

Of course this will depend on the students but scaffolding the learning in this manner may make these concepts easier to understand.

Our micro:bit course lessons are tailored to apply knowledge obtained from the Code.org CS Fundamentals. Before students begin this lesson, they are encouraged to first complete all CS Fundamentals as a prerequisite. Students should be familiar with functions from Code.org CS Fundamentals.

Background

Students are highly encouraged to first complete the following:

The teacher is highly encouraged to read below and complete the following:

Teacher Guide

Open

Activity

What you'll need

  • 1 - micro:bit
  • 1 - USB cable
  • 1 - AAA battery pack (optional)
  • 2 - AAA batteries (optional)

Documentation


function doSomething()  {
    basic.showString("Hello!")
}

doSomething()
            

function

A function lets you create a portion of code that you can reuse in your program.

basic.showIcon(IconNames.Heart)

showIcon

Shows the selected icon on the LED screen


input.onGesture(Gesture.Shake, () => {

})
            

onGesture

Start an event handler (part of the program that will run when something happens) This handler works when you do a gesture (like shaking the micro:bit).


input.onButtonPressed(Button.A, () => {

})
            

onButtonPressed

Start an event handler (part of the program that will run when something happens, like when a button is pressed)

4 steps

Guided Practice

We will make instructions or code online for the micro:bit. Next, go to: makecode.microbit.org

let KeepRunning = false
let KilometersRan = 0
let XRunningPosition = 0
let YRunningPosition = 0
input.onButtonPressed(Button.A, () => {
    Run_FasterThan_A_Speeding_Bullet()
})
function Run_FasterThan_A_Speeding_Bullet()  {
    KilometersRan = 0
    KeepRunning = true
    XRunningPosition = 0
    YRunningPosition = 0
    for (let YRunningPosition = 0; YRunningPosition <= 5; YRunningPosition++) {
        for (let XRunningPosition = 0; XRunningPosition <= 5; XRunningPosition++) {
            led.plot(XRunningPosition, YRunningPosition)
            led.unplot(XRunningPosition - 1, YRunningPosition - 1)
            basic.pause(70)
        }
    }
}
input.onButtonPressed(Button.B, () => {
    MagicUsedToConjure()
})
function Object_Your_Superhero_Can_Conjure()  {

}
function MagicUsedToConjure()  {
    for (let index = 0; index <= 4; index++) {
        Object_Your_Superhero_Can_Conjure()
        basic.clearScreen()
        basic.pause(150)
    }
}

This code calls some fairly complicated functions(Run_FasterThan_A_Speeding_Bullet, Magic-Used-To-Conjure) but the details of how these two functions work is not really important to this lesson. Placing the calls to those functions is the crux of this lesson. Where and how do you call these functions? Where should certain blocks of code start?

Seeing an example of how functions can help organize your coding problems is also the intention of this lesson.

For this lesson we look at a superhero.

Pressing A calls our Run_FasterThan_A_Speeding_Bullet function. This shows the LEDs "running across the screen". Our hero can really move.

Pressing B and shaking the micro:bit will make the superhero do other super powers. This is what the students need to help develop in the challenges. Pressing B causes the superhero to conjure or create an object. It should be a blinking icon or picture made with show LEDs or show icon. The task is for students to determine what the superhero can conjure and students should also create a story that tells why the superhero would use this ability. The on shake challenge is similar.

The finished code is available here.

Simple Function Challenges

Challenge 1

Can you make the superhero conjure an object? Create a story connected to this idea.

Hint: Place something in the Object_Your_Superhero_Can_Conjure function. Show what they can magically produce.

View code

Example - I used the show ghost icon block. My superhero can conjure ghosts and scare people. This is fun on elevators.

let YRunningPosition = 0
let XRunningPosition = 0
let KeepRunning = false
let KilometersRan = 0
input.onButtonPressed(Button.B, () => {
    MagicUsedToConjure()
})
function MagicUsedToConjure()  {
    for (let index = 0; index <= 4; index++) {
        Object_Your_Superhero_Can_Conjure()
        basic.clearScreen()
        basic.pause(150)
    }
}
function Object_Your_Superhero_Can_Conjure()  {
    basic.showIcon(IconNames.Ghost)
}
input.onButtonPressed(Button.A, () => {
    Run_FasterThan_A_Speeding_Bullet()
})
function Run_FasterThan_A_Speeding_Bullet()  {
    KilometersRan = 0
    KeepRunning = true
    XRunningPosition = 0
    YRunningPosition = 0
    for (let YRunningPosition2 = 0; YRunningPosition2 <= 5; YRunningPosition2++) {
        for (let XRunningPosition2 = 0; XRunningPosition2 <= 5; XRunningPosition2++) {
            led.plot(XRunningPosition2, YRunningPosition2)
            led.unplot(XRunningPosition2 - 1, YRunningPosition2 - 1)
            basic.pause(70)
        }
    }
}
input.onGesture(Gesture.Shake, () => {

})

The finished code is available here

Challenge 2

Can you make the superhero do something else when we shake the micro:bit? Create a story connected to this idea.

View code

Example - Answers will vary.... The example has the micro:bit showing a surprised icon. The hero is surprised when shaken by anyone.

let YRunningPosition = 0
let XRunningPosition = 0
let KeepRunning = false
let KilometersRan = 0
input.onButtonPressed(Button.B, () => {
    MagicUsedToConjure()
})
function MagicUsedToConjure()  {
    for (let index = 0; index <= 4; index++) {
        Object_Your_Superhero_Can_Conjure()
        basic.clearScreen()
        basic.pause(150)
    }
}
function Object_Your_Superhero_Can_Conjure()  {
    basic.showIcon(IconNames.Ghost)
}
input.onButtonPressed(Button.A, () => {
    Run_FasterThan_A_Speeding_Bullet()
})
function Run_FasterThan_A_Speeding_Bullet()  {
    KilometersRan = 0
    KeepRunning = true
    XRunningPosition = 0
    YRunningPosition = 0
    for (let YRunningPosition2 = 0; YRunningPosition2 <= 5; YRunningPosition2++) {
        for (let XRunningPosition2 = 0; XRunningPosition2 <= 5; XRunningPosition2++) {
            led.plot(XRunningPosition2, YRunningPosition2)
            led.unplot(XRunningPosition2 - 1, YRunningPosition2 - 1)
            basic.pause(70)
        }
    }
}
input.onGesture(Gesture.Shake, () => {
    basic.showIcon(IconNames.Surprised)
})

Some example code is available here

Independent Practice

Create your own micro:bit superhero by changing things in the existing function blocks and event handler. Your superhero should do 3 new super powers. Changing icons or LEDs can create a new superhero. Be prepared to tell a story about the new hero and why it does the actions you choose.

Starting code can be found here.

Quiz

Use these questions to reflect on the activity and challenges.

Question 1

What is one benefit of using functions?

Show answer

Any of these is an acceptable answer

  1. Functions allow us to repeat code without retyping it so code is smaller.
  2. If we need to make changes, we only have to change our code in one place.
  3. Functions allow us to organize our code better.

Question 2

What is an event that starts/calls a function in this code?

Show answer
on shake
on button A pressed
on button B pressed

Question 3

Think of something that could use the concept of functions(breaking repeating activities into reusable pieces) and list the actions you could put into functions. An example might be a game console.

Show answer
Game Console Functions
Start Game
Show Menu
Save Game
etc

Another example might be making an ice cream cone.

Making Ice Cream Cone Functions
Choose Flavor
Grab Cone
Scoop Ice Cream
Put Scoop on Cone
EAT!!!
Selecting this opens external content from our support system, which adheres to their privacy policy.