python趣味例程:microbit萤火虫

micro:bit编程、教学、展示
STEM
回复
头像
shaoziyang
帖子: 3919
注册时间: 2019年 10月 21日 13:48

python趣味例程:microbit萤火虫

#1

帖子 shaoziyang »

萤火虫是一种群居的生物,夏日夜晚,在公园或者树林里,萤火虫会一闪一闪,非常好看。 在科学中,根据萤火虫的特性也有一种特殊的算法叫做萤火虫算法,它模拟自然界中萤火虫发光的生物学特性,控制群体中单个个体的行为,是一种基于群体的随机优化算法。
 
图片
 

在micro:bit的python源码的例程中有一个无线(radio)通信的例子,它通过无线方式,模拟萤火虫之间互相呼应的效果。

这个例程需要多个microbit,最少需要5个以上,数量越多效果越好。

开始的时候,需要随机选择一个microbit,按下A键,通过无线发送“flash”(闪光)命令,启动系统。其它microbit接受到信号后,随机延时 50 - 350ms,然后以显示一组动画画面(屏幕从亮变暗)。最后产生一个随机数,如果随机数的值是零,就将发送“flash”命令。如果microbit的数量足够多,整个过程就会不断持续下去,形成此起彼伏,互相呼应的效果。

代码: 全选

# A micro:bit Firefly.
# By Nicholas H.Tollervey. Released to the public domain.
import radio
import random
from microbit import display, Image, button_a, sleep

# Create the "flash" animation frames. Can you work out how it's done?
flash = [Image().invert()*(i/9) for i in range(9, -1, -1)]

# The radio won't work unless it's switched on.
radio.on()

# Event loop.
while True:
    # Button A sends a "flash" message.
    if button_a.was_pressed():
        radio.send('flash')  # a-ha
    # Read any incoming messages.
    incoming = radio.receive()
    if incoming == 'flash':
        # If there's an incoming "flash" message display
        # the firefly flash animation after a random short
        # pause.
        sleep(random.randint(50, 350))
        display.show(flash, delay=100, wait=False)
        # Randomly re-broadcast the flash message after a
        # slight delay.
        if random.randint(0, 9) == 0:
            sleep(500)
            radio.send('flash')  # a-ha
图片
 

头像
shaoziyang
帖子: 3919
注册时间: 2019年 10月 21日 13:48

Re: python趣味例程:microbit萤火虫

#2

帖子 shaoziyang »


回复

  • 随机主题
    回复总数
    阅读次数
    最新文章