# Course E - Functions 2 - Functions for a Digital Pet

This lesson introduces the concept of functions.

• 대상 연령 9+
• 65+ 예상 시간(분)
• MakeCode Editor

## 소개

If you have forgotten what functions are and need a review, please revisit the introduction in the lesson 'A SIMPLE FUNCTION FOR A SUPERHERO'. This was the first lesson in this series on functions.

Our current lesson builds upon 'A SIMPLE FUNCTION FOR A SUPERHERO' in two ways.

First, the importance of using functions to organize code is reiterated. Functions allow us to organize code in logical ways. We can arrange code so that it is easier to "see" the real life objects we want to simulate. Here that is demonstrated again with the pets actions.

Second, we build upon the previously introduced benefit of reusing code. Functions allow us to easily reuse code. In this lesson learners are challenged a bit more on this concept. They are asked to identify which part of the code would be best suitable for a function. This is in Challenge 3.

마이크로비트 코스 레슨들은 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:

## 활동

준비물

• 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.

``````
for(let i = 0; i < 5; ++i) {
basic.showNumber(i)
}
``````

### 반복(for)

원하는 코드를 원하는 횟수만큼 반복 실행 시킵니다.

``````
basic.showLeds(`
. . . . .
. . . . .
. . # . .
. . . . .
. . . . .
`)
``````

### LED 출력

LED 스크린 화면에 이미지를 출력합니다.

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

})
``````

### 버튼 누르면 실행

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

``basic.showIcon(IconNames.Heart)``

### 아이콘 출력

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

``basic.pause(100)``

### pause

Pause the program for the number of milliseconds you say. -

``````
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).

5 steps

## Designing Our Pet

Draw three 5 by 5 grids and color in the boxes (representing LEDs) to show what your pet will look like awake, asleep, and drinking.

Here we have chosen the following but you can do anything you like.

1. Smiley Face = awake
2. Z displaying 4 times = asleep (When button A is pushed)
3. Water Drop displays 4 times = drinking (When button B is pushed)

Our pet, Herbert, will be a happy little guy when he is awake so we display a smiley face.

Sometimes we need to sleep and Herbert should too. We will make him sleep by petting him. Pressing button A pets Herbert and ZZZZ (Z 4 times blinking) will appear to show he is sleeping.

Then he goes quiet (LEDs off) as he dreams. To wake him, we give him some water. Herbert loves water so we can give it to him whenever we like. This will wake him and also return him to a happy state again. We will give him water by pressing button B. A water drop will appear to show he is drinking and then he wakes up again and shows a smiley face again!

## 따라해보기

마이크로비트를 위한 단계별 설명이나 온라인 코드를 제공할 예정입니다. makecode.microbit.org 로 접속해보세요.

``````input.onButtonPressed(Button.B, () => {
DRINKING()
})
function ASLEEP()  {
for (let i = 0; i < 4; i++) {
basic.showLeds(`
# # # # #
. . . # .
. . # . .
. # . . .
# # # # #
`)
basic.pause(500)
basic.clearScreen()
basic.pause(500)
}
}
function DRINKING()  {
for (let index = 0; index <= 4; index++) {
basic.showLeds(`
. . # . .
. # . # .
# . . . #
# . . . #
. # # # .
`)
basic.pause(500)
basic.clearScreen()
basic.pause(500)
}
AWAKE()
}
input.onButtonPressed(Button.A, () => {
ASLEEP()
})
function AWAKE()  {
basic.showIcon(IconNames.Happy)
}
input.onGesture(Gesture.Shake, () => {

})
function EXERCISE()  {

}
input.onButtonPressed(Button.AB, () => {

})
AWAKE()
``````

Herbert has three functions he does. He is either awake, asleep, or drinking. We have a function for each of these actions.

On start, we call the function that displays a happy face. Herbert is happy and awake.

Pressing button A calls a function that displays a flashing Z. This means Herbert is sleeping.

Pressing button B calls a function that displays a flashing waterdrop. This means Herbert is drinking.

The only real difference between the ASLEEP and DRINKING functions is at the end. At the end of the DRINKING function, we call the AWAKE function again and Herbert shows his happy face. Herbert likes water.

Pauses and clearing the screen help us create a blinking effect. The for and repeat loops also contribute to make the blinking effect.

The details of how the two functions(ASLEEP, DRINKING) work is not really important to this lesson. Placing the calls to those functions and understanding how to build our own function will be our focus.

The finished base code without challenges completed is available here.

안내: 코드의 아래쪽에 있는 사용되지 않은 블록들은 도전과제에서 사용될 것입니다.

## 함수 도전하기

### 도전과제 1

Can you program Herbert to exercise when both buttons A and B are pushed?

Hint: Use the exercise function, roller skate icon, and A+B event handler.

View code
``````function AWAKE()  {
basic.showIcon(IconNames.Happy)
}
function ASLEEP()  {
for (let i = 0; i < 4; i++) {
basic.showLeds(`
# # # # #
. . . # .
. . # . .
. # . . .
# # # # #
`)
basic.pause(500)
basic.clearScreen()
basic.pause(500)
}
}
function DRINKING()  {
for (let index = 0; index <= 4; index++) {
basic.showLeds(`
. . # . .
. # . # .
# . . . #
# . . . #
. # # # .
`)
basic.pause(500)
basic.clearScreen()
basic.pause(500)
}
AWAKE()
}
input.onButtonPressed(Button.A, () => {
ASLEEP()
})
input.onButtonPressed(Button.B, () => {
DRINKING()
})
input.onButtonPressed(Button.AB, () => {
EXERCISE()
})
function EXERCISE()  {
basic.showIcon(IconNames.Rollerskate)
}
input.onGesture(Gesture.Shake, () => {

})
AWAKE()``````

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

### 도전과제 2

Can you program Herbert to do a new action on shake?

View code
``````input.onButtonPressed(Button.B, () => {
DRINKING()
})
function Silly()  {
basic.showIcon(IconNames.Rollerskate)
}
function ASLEEP()  {
for (let i = 0; i < 4; i++) {
basic.showLeds(`
# # # # #
. . . # .
. . # . .
. # . . .
# # # # #
`)
basic.pause(500)
basic.clearScreen()
basic.pause(500)
}
}
function DRINKING()  {
for (let index = 0; index <= 4; index++) {
basic.showLeds(`
. . # . .
. # . # .
# . . . #
# . . . #
. # # # .
`)
basic.pause(500)
basic.clearScreen()
basic.pause(500)
}
AWAKE()
}
input.onButtonPressed(Button.A, () => {
ASLEEP()
})
function AWAKE()  {
basic.showIcon(IconNames.Happy)
}
input.onButtonPressed(Button.AB, () => {
EXERCISE()
})
input.onGesture(Gesture.Shake, () => {
Silly()
})
function EXERCISE()  {
basic.showIcon(IconNames.Rollerskate)
}
AWAKE()
``````

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

### 도전과제 3

If you remember, one benefit of functions is writing code and then being able to reuse it easily. Look at the ASLEEP and DRINKING functions. What code is the same? Can you make a new function for this repeating code? Call your function BLINKING.

View code
``````input.onButtonPressed(Button.B, () => {
DRINKING()
})
basic.pause(500)
basic.clearScreen()
basic.pause(500)
}
function ASLEEP()  {
for (let i = 0; i < 4; i++) {
basic.showLeds(`
# # # # #
. . . # .
. . # . .
. # . . .
# # # # #
`)
}
}
function DRINKING()  {
for (let index = 0; index <= 4; index++) {
basic.showLeds(`
. . # . .
. # . # .
# . . . #
# . . . #
. # # # .
`)
basic.pause(500)
basic.clearScreen()
basic.pause(500)
}
AWAKE()
}
input.onButtonPressed(Button.A, () => {
ASLEEP()
})
function AWAKE()  {
basic.showIcon(IconNames.Happy)
}
input.onButtonPressed(Button.AB, () => {
EXERCISE()
})
input.onGesture(Gesture.Shake, () => {
Silly()
})
function EXERCISE()  {
basic.showIcon(IconNames.Rollerskate)
}
function Silly()  {
basic.showIcon(IconNames.Rollerskate)
}
AWAKE()``````

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

## 자기주도 연습

Create your own micro:bit pet with 3 function calls. Inserting icons or changing LEDs can create a new pet. Be prepared to tell a story about the new pet and why it does the actions you choose.

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

## 퀴즈

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

### 질문 1

What is one benefit of using functions?

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

How do I make the code in a function "go" or "start"?

Call a function and the code inside will "go"

### 질문 3

Think of something that could use functions and list what you could put in functions. An example might be a car.