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

This lesson introduces the concept of functions.

  • Computer science
  • functions
Print lesson
  • 대상 연령 9+
  • 65+ 예상 시간(분)
  • JavaScript Blocks

소개

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.

마이크로비트 코스 레슨들은 Code.org CS 기초 과정에서 배운 지식들을 적용하는 내용들로 맞춰져 있습니다. 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.

배경

학생들은, 다음을 먼저 완료하는 것이 매우 좋습니다.

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

교사용 가이드

Open

활동

준비물

  • BBC 마이크로비트 1대
  • USB 케이블 1개
  • AAA 배터리 팩 (옵션)
  • AAA 배터리 2개 (옵션)

수업 자료


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

doSomething()
            

함수

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

basic.showIcon(IconNames.Heart)

아이콘 출력

선택한 아이콘을 LED 스크린 화면에 출력합니다.


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

})
            

움직임 감지하면 실행

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, () => {

})
            

버튼 누르면 실행

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

4 단계

따라해보기

마이크로비트를 위한 단계별 설명이나 온라인 코드를 제공할 예정입니다. 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

도전과제 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, () => {

})

완성된 코드는 여기 에서 살펴볼 수 있습니다

도전과제 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)
})

예시 코드는 여기 에서 살펴볼 수 있습니다

자기주도 연습

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.

시작 코드는 여기 에서 살펴볼 수 있습니다.

퀴즈

다음과 같은 질문들을 사용해, 학습활동과 도전과제들에 대해서 다시 기억해 내도록 할 수 있습니다.

질문 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.

질문 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

질문 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.