活动#

介绍#

事件允许您并行运行函数。您无需按顺序调用函数,而是可以将多个函数注册到一个事件中,并一次性触发它们。每个注册的函数都在其自身的线程中运行,从而使您的机器人能够同时执行多个任务——例如在行驶过程中在屏幕上显示数值。

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

  1. Create the event with Event.

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

  3. Broadcast an Event:

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

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

创建活动#

Event creates an event object that manages function execution in separate threads.

用法:
Event()

参数

描述

此构造函数没有参数。

# Build Used: Super Code Base 2.0
def move_square():
    for index in range(4):
        drivetrain.drive_for(FORWARD, 150)
        drivetrain.turn_for(RIGHT, 90)

def main():
    # Creating the move_event Event
    move_event = Event()
    move_event(move_square)
    move_event.broadcast()
    bumper.set_color(GREEN)

# Start threads — Do not delete
start_thread(main)

将函数注册到事件#

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

Usage:
event(callback, args)

参数

描述

event

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

callback

预先定义的函数,将在事件广播时执行。

args

可选。要传递给回调函数的参数元组。

# Build Used: Super Code Base 2.0
def move_square():
    for index in range(4):
        drivetrain.drive_for(FORWARD, 150)
        drivetrain.turn_for(RIGHT, 90)

def main():
    move_event = Event()
    # Register the move_square function to the move_event Event
    move_event(move_square)
    move_event.broadcast()
    bumper.set_color(GREEN)

# Start threads — Do not delete
start_thread(main)

直播活动#

broadcast#

broadcast triggers an event, starting all registered functions in separate threads. This method does not pause execution of any subsequent code.

用法:
event.broadcast()

参数

描述

event

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

# Build Used: Super Code Base 2.0
def move_square():
    for index in range(4):
        drivetrain.drive_for(FORWARD, 150)
        drivetrain.turn_for(RIGHT, 90)

def main():
    move_event = Event()
    move_event(move_square)
    # Broadcasting the move_event Event
    move_event.broadcast()
    bumper.set_color(GREEN)

# Start threads — Do not delete
start_thread(main)

broadcast_and_wait#

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

用法:
event.broadcast_and_wait()

参数

描述

event

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

# Build Used: Super Code Base 2.0
def move_square():
    for index in range(4):
        drivetrain.drive_for(FORWARD, 150)
        drivetrain.turn_for(RIGHT, 90)

def main():
    # Set up and call the move_square event
    move_event = Event()
    move_event(move_square)
    # Broadcast the move_event Event and wait
    move_event.broadcast_and_wait()
    bumper.set_color(GREEN)

# Start threads — Do not delete
start_thread(main)