# Guess The Number

• 年齡 8+
• 30 分
• MakeCode Editor

## 介紹

Second project using the MakeCode editor and introduces the students to the use of variables, user inputs and random numbers. When the button is pressed a random number between a given range is shown.

## 活動

5 steps

### Step One

In the MakeCode editor select the Input option from the block menu and find the “On button pressed” block and drag onto the workspace.

``````
input.onButtonPressed(Button.A, function () {

})
``````

Once on the workspace the button variable can be changed to either “A”, “B” or “A+B”. In this case select “A”. Code that is then placed inside this input will only happen when the button is pressed.

### Step Two

From the block menu select the “Variable” and click “Make a Variable”. A variable is where data can be stored. A popup dialogue box will then ask you to name your variable. In this example name it “X” ### Step Three

Still in the Variables option in the block menu select the “Set item to 0” block. This will enable a variable to be set to a given value. Move the “Set variable to” block inside the “On button” block. Now when the button “A” is pressed the variable “item” will be set to 0.

``````
let item = 0
input.onButtonPressed(Button.A, function () {
item = 0
})
``````

The variable name can be changed by selecting the down arrow next to the word item and changed to a different variable. As we have created a “X” variable, select this.

``````
let X = 0
input.onButtonPressed(Button.A, function () {
X = 0
})
``````

### Step Four

The next element is to build a random number element within the program. From the block menu select the “Math” option and select “pick random 0 to 10” We would like to set the variable “X” to be a random number, so drag the random number block and replace the “0” with the random block.

``````
let X = 0
input.onButtonPressed(Button.A, function () {
X = Math.randomRange(0, 10)
})
``````

As we would like the random number to be in the range from 0 to 9, click the “10” and replace it with “9”.

``````
let X = 0
input.onButtonPressed(Button.A, function () {
X = Math.randomRange(0, 9)
})
``````

### Step Five

The next stage is to show the random number on the LEDs. From the Basic option in the block menu select show number and drag onto the workspace. Move the “Show number” block below the “set X” block. This will now show the number 0 if the program was run.

``````
let X = 0
input.onButtonPressed(Button.A, function () {
X = Math.randomRange(0, 9)
basic.showNumber(0)
})
``````

To show the random number we need to set the show number block to the variable “X”. From the Variable option in the block menu select the “X” variable block and drag onto the workspace. Move the “X” variable block into the show number.

``````
let X = 0
input.onButtonPressed(Button.A, function () {
X = Math.randomRange(0, 9)
basic.showNumber(X)
})
``````