1. 文档中心
  2. 比卜创造 Micro:bit
  3. Python
  4. 手势

手势

有了加速度计,一件特别有趣的事就是手势检测。当你以某种方式移动 micro:bit(做出一个手势)时,BiBoPython 就能识别出来。

BiBoPython 能识别这些手势:up、down、left、right、face up、face down、freefall、3g、6g、8g、shake。手势始终以字符串表示。大部分名字很好理解;3g、6g、8g 表示设备受到相应倍数的重力加速度——就像宇航员被发射升空时感受到的那种力。

要获取当前手势,使用 accelerometer.current_gesture 方法,返回值是上面列出的手势名之一。例如,下面这段程序只有在屏幕朝上时才会让 micro:bit「开心」:

from bibo import *

while True:
    gesture = accelerometer.current_gesture()
    if gesture == "face up":
        display.show(Image.HAPPY)
    else:
        display.show(Image.ANGRY)

和前面几课一样,我们希望设备能对变化做出反应,所以用了 while 循环。在循环作用域内,读取当前手势并存入 gesture。if 判断 gesture 是否等于 "face up"(Python 用 == 测试相等,单个 = 用于赋值——就像我们把手势读数赋给 gesture 一样)。若朝上,就显示开心脸;否则显示生气脸!

魔法 8 球

魔法 8 球是 20 世纪 50 年代发明的玩具:向它提一个是非问题,摇一摇,等它给出「答案」。做成程序也很简单:

from bibo import *
import random

answers = [
    "It is certain",
    "It is decidedly so",
    "Without a doubt",
    "Yes, definitely",
    "You may rely on it",
    "As I see it, yes",
    "Most likely",
    "Outlook good",
    "Yes",
    "Signs point to yes",
    "Reply hazy try again",
    "Ask again later",
    "Better not tell you now",
    "Cannot predict now",
    "Concentrate and ask again",
    "Don't count on it",
    "My reply is no",
    "My sources say no",
    "Outlook not so good",
    "Very doubtful",
]

while True:
    display.show("8")
    if accelerometer.was_gesture("shake"):
        display.clear()
        sleep(1000)
        display.scroll(random.choice(answers))

程序主体是一个叫 answers 的列表;真正的「游戏逻辑」在末尾的 while 循环里。

默认状态是显示字符 "8"。程序需要检测是否被摇动:was_gesture 方法接受一个参数(这里是 "shake"),返回 True 或 False。若设备被摇过,if 进入代码块:清屏、等待一秒(像在想你的问题),再滚动显示随机选出的答案。

不妨问它:这是不是史上最棒的程序?你怎样「作弊」,让答案总是肯定或否定?(提示:用按钮。)

本页目录