# 魔术按钮活动

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

## 课堂活动

6个步骤

This is a simple magic trick you can perform to amaze your friends by magically switching the A and B buttons on the micro:bit!

### 步骤1：让按钮显示A和B

``````
input.onButtonPressed(Button.A, function () {
basic.showString("A")
})
input.onButtonPressed(Button.B, function () {
basic.showString("B")
})
``````

### 步骤3：检查附近是否有磁场

``````
let isSwitched = false
let force = 0

force = Math.abs(input.magneticForce(Dimension.Strength))
isSwitched = force > 100
``````

### 步骤4：运行我们的“magnet nearby”（附近的磁场）始终保持检查

At the moment our code to detect the magnet being nearby will only run once so we need to put it into a forever block so that it keeps getting run again and again checking for the magnet to come near to the micro:bit. 我们也应该确保程序启动的时候，“isSwitched”是false（假的）。

``````
let isSwitched = false
let force = 0
basic.forever(function () {
force = Math.abs(input.magneticForce(Dimension.Strength))
isSwitched = force > 100
})
``````

### 步骤5：检测到附近的磁铁后，切换按钮

``````
let isSwitched = false
let force = 0
input.onButtonPressed(Button.A, function () {
if (isSwitched) {
basic.showString("B")
} else {
basic.showString("A")
}
})
input.onButtonPressed(Button.B, function () {
if (isSwitched) {
basic.showString("A")
} else {
basic.showString("B")
}
})
``````

### 步骤6：表演练习

Here is the finished code:

``````
let isSwitched = false
let force = 0
input.onButtonPressed(Button.A, function () {
if (isSwitched) {
basic.showString("B")
} else {
basic.showString("A")
}
})
input.onButtonPressed(Button.B, function () {
if (isSwitched) {
basic.showString("A")
} else {
basic.showString("B")
}
})
basic.forever(function () {
force = Math.abs(input.magneticForce(Dimension.Strength))
isSwitched = force > 100
})
``````

Now you just need to program your own micro:bit and practice the trick a few times before performing to friends. Try asking your friends to click the buttons after you have switched the labels and the trick won’t work for them as they don’t have a hidden magnet in their hand.

## 挑战

• 当超过了一定的磁力强度之后，添加一个动画。
• 按下“A+B”按钮，出现了一个磁性读取选项。