活动#

介绍#

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

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

  • Event – Creates a new event object.

  • 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.

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

Create an Event Object#

The Event constructor is used to create an event object that manages function execution in separate threads.

Usage:
Event()

范围

描述

此构造函数没有参数。

def dash_lines():
    # Move the pen up and down
    while True:
        pen.move(DOWN)
        wait(0.5, SECONDS)
        pen.move(UP)
        wait(0.5, SECONDS)

def main():
    # Set the event
    move_event = Event()
    move_event(dash_lines)
    # Draw the dash line while driving forward
    move_event.broadcast()
    drivetrain.drive_for(FORWARD, 1000, MM)

# VR threads — Do not delete
vr_thread(main)

Broadcast#

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

Usage:
my_event.broadcast()

范围

描述

event

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

def dash_lines():
    # Move the pen up and down
    while True:
        pen.move(DOWN)
        wait(0.5, SECONDS)
        pen.move(UP)
        wait(0.5, SECONDS)

def main():
    # Set the event
    move_event = Event()
    move_event(dash_lines)
    # Draw the dash line while driving forward
    move_event.broadcast()
    drivetrain.drive_for(FORWARD, 1000, MM)

# VR threads — Do not delete
vr_thread(main)

Broadcast and wait#

broadcast_and_wait starts an event but waits for all registered functions to finish before continuing with subsequent functions.

Usage:
my_event.broadcast_and_wait()

范围

描述

event

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

def move_and_turn():
    # Drive forward and turn
    drivetrain.drive_for(FORWARD, 150, MM)
    drivetrain.turn_for(RIGHT, 90, DEGREES)

def main():
    # Wait for the event to finish after 3 seconds
    move_event = Event()
    move_event(move_and_turn)
    while True:
        if brain.timer_time(SECONDS) > 3:
            move_event.broadcast_and_wait()
            break
        wait(5, MSEC)
    brain.print("Movement done.")

# VR threads — Do not delete
vr_thread(main)

Register Functions to an Event#

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

Usage:
event(callback, args)

范围

描述

event

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

callback

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

def dash_lines():
    # Move the pen up and down
    while True:
        pen.move(DOWN)
        wait(0.5, SECONDS)
        pen.move(UP)
        wait(0.5, SECONDS)

def main():
    # Set and call the event and start driving
    move_event = Event()
    move_event(dash_lines)
    move_event.broadcast()
    drivetrain.drive(FORWARD)

# VR threads — Do not delete
vr_thread(main)