活动#

介绍#

事件允许您使用事件对象并行运行函数。无需逐个调用函数或线程,事件允许您注册函数,然后一次性触发所有函数。每个注册函数都在其自己的线程中运行,因此您的机器人可以同时执行多项操作,例如 LED 闪烁和驾驶。

以下是可用方法和构造函数的列表:

  • Event – Creates a new event object.

  • event – Registers a function to the event object, optionally with arguments.

  • broadcast – Triggers all registered functions in an event object to run in parallel.

  • broadcast_and_wait – Triggers all registered functions in an event object and waits for them to finish before continuing.

Create an Event Object#

Event 构造函数用于创建一个事件对象,该对象在单独的线程中管理函数的执行。

用法:
Event()

范围

描述

此构造函数没有参数。

# Blink LEDs while moving forward
# Create move_event as an Event object
move_event = Event()

def blink_leds():
    while True:
        robot.led.on(ALL_LEDS, RED)
        wait(0.5, SECONDS)
        robot.led.on(ALL_LEDS, BLACK)
        wait(0.5, SECONDS)

move_event(blink_leds)
move_event.broadcast()
robot.move_at(0)

Register Functions to an Event#

当您将一个函数注册到某个事件时,它将在事件广播时在单独的线程中执行。

用法:
event(callback, args)

范围

描述

event

先前创建的事件对象的名称。

callback

先前定义的在事件广播时执行的函数。

args

Optional. A tuple containing arguments to pass to the callback function. See Using Functions with Parameters for more information.

# Blink LEDs while moving forward and turning
move_event = Event()

def blink_leds():
    while True:
        robot.led.on(ALL_LEDS, RED)
        wait(0.5, SECONDS)
        robot.led.on(ALL_LEDS, BLACK)
        wait(0.5, SECONDS)

def turning():
    robot.turn(RIGHT)

# Register multiple functions to the Event object
move_event(blink_leds)
move_event(turning)

move_event.broadcast()

# Move in a specified direction
move_event = Event()

def move_distance(movement_angle):
    robot.move_for(50, movement_angle)

# Change the parameter to modify how the robot moves
move_event(move_distance, (180,))
move_event.broadcast()

Broadcast#

broadcast 会触发一个事件,并在单独的线程中启动所有已注册的函数。此方法不会暂停任何后续函数的执行。

用法:
event.broadcast()

范围

描述

event

先前创建的事件对象的名称。

# Blink LEDs while moving forward and turning
move_event = Event()

def blink_leds():
    while True:
        robot.led.on(ALL_LEDS, RED)
        wait(0.5, SECONDS)
        robot.led.on(ALL_LEDS, BLACK)
        wait(0.5, SECONDS)


move_event(blink_leds)

# Trigger the move_event Event
move_event.broadcast()
robot.move_at(0)

Broadcast and wait#

broadcast_and_wait 启动一个事件,但等待所有已注册的函数完成后再继续执行后续函数。

用法:
event.broadcast_and_wait()

范围

描述

event

先前创建的事件对象的名称。

# Move after the screen is pressed
move_event = Event()

def move_and_turn():
    robot.move_for(50, 0)
    robot.turn_for(RIGHT, 90)

move_event(move_and_turn)

while True:
    if robot.screen.pressing():
        move_event.broadcast_and_wait()
        break
robot.screen.print("Movement done.")