# 掷骰子活动

Create virtual dice using the MakeCode editor

• 年龄 8+
• 30 分钟
• MakeCode Editor

## 课堂活动

5个步骤

### 第一步

This is a program that allows the user to shake the micro:bit to show a die face. On the MakeCode editor select the input blocks from the block menu and select the “shake” block.

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

})
``````

### 第二步

``````
let item = 0
input.onGesture(Gesture.Shake, () => {
item = 0
})
``````

Rename the variable to something more suitable, such as “Roll”. Click the arrow next to 'item' and select 'Rename variable'; a popup box will allow you to change the variable name.

Now that a variable called “Roll” has been created we needed to pick a random number between 1 and 6. From the block menu select the “Math” option and select “pick random 0 to 10”

Drag the “pick random” block onto the workspace and connect it to the “Set variable” block replacing the “0” with “1” and the “10” with “6”. Now the program will pick a random number between 1 and 6 every time the micro:bit is shaken. 这个数将会存储在变量“Roll”（滚动）中。

``````
let roll = 0
input.onGesture(Gesture.Shake, function () {
roll = Math.randomRange(1, 6)
})
``````

### 第三步

Add a logic statement of “IF THEN ELSE” and click the "+" button to edit the logic to have multiple conditions.

``````
let roll = 0
input.onGesture(Gesture.Shake, function () {
roll = Math.randomRange(1, 6)
if (true) {

} else {

}
})
``````

``````
let roll = 0
input.onGesture(Gesture.Shake, function () {
roll = Math.randomRange(1, 6)
if (true) {

} else if (false) {

} else if (false) {

} else if (false) {

} else if (false) {

} else {

}
})
``````

### 第四步

The first of the 6 checks to carry out is if the variable “Roll” is equal to 1. Place the “Roll” variable within the “is equal to” (=) block.

``````
let roll = 0
input.onGesture(Gesture.Shake, function () {
roll = Math.randomRange(1, 6)
if (roll == 1) {

} else if (roll == 2) {

} else if (roll == 3) {

} else if (roll == 4) {

} else if (roll == 5) {

} else {

}
})
``````

### 第五步

``````
let roll = 0
input.onGesture(Gesture.Shake, function () {
roll = Math.randomRange(1, 6)
if (roll == 1) {
basic.showLeds(`
. . . . .
. . . . .
. . # . .
. . . . .
. . . . .
`)
} else if (roll == 2) {
basic.showLeds(`
. . . . .
. . . # .
. . . . .
. # . . .
. . . . .
`)
} else if (roll == 3) {
basic.showLeds(`
# . . . .
. . . . .
. . # . .
. . . . .
. . . . #
`)
} else if (roll == 4) {
basic.showLeds(`
. . . . .
. # . # .
. . . . .
. # . # .
. . . . .
`)
} else if (roll == 5) {
basic.showLeds(`
. . . . .
. # . # .
. . # . .
. # . # .
. . . . .
`)
} else {
basic.showLeds(`
. # . # .
. . . . .
. # . # .
. . . . .
. # . # .
`)
}
})
``````

## 挑战

• 添加一个骰子滚动的动画。
• 允许用户声明骰子面的数字，即6、8或12