事件#

简介#

Events allow you to run functions in parallel. Instead of calling functions sequentially, you can register multiple functions to an event and trigger them all at once. Each registered function runs in its own thread, enabling your robot to perform multiple tasks simultaneously—like displaying values on the screen while driving.

要创建和使用事件,请按以下步骤操作:

  1. 使用[Event] (#create-an-event)创建活动。

  2. Register a function to trigger when the Event is broadcast by calling the event object with the function as an argument.

  3. 广播 Event

    • [broadcast] (#broadcast) –触发事件对象中已注册的所有函数并发运行。

    • [broadcast_and_wait] (#broadcast-and-wait) –触发事件对象中已注册的所有函数,并等待它们完成后再继续。

创建事件#

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

Usage:
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)

将函数注册到事件#

When you register a function to an event, it will execute in a separate thread when the event is broadcast.

Usage:
event(callback, args)

参数

描述

event

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

callback

A previously defined function to execute when the event is broadcast.

args

Optional. A tuple of arguments to pass to the callback function.

# 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 触发一个事件,在单独的线程中启动所有已注册的函数。此方法不会暂停任何后续函数的执行。

Usage:
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 开始一个事件,但等待所有注册的函数完成,然后继续后续函数。

Usage:
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.")