事件#
简介#
事件允许您并行运行函数。您无需按顺序调用函数,而是可以将多个函数注册到一个事件中,并一次性触发它们。每个注册的函数都在其自身的线程中运行,从而使您的机器人能够同时执行多个任务——例如在行驶过程中在屏幕上显示数值。
要创建和使用事件,请按以下步骤操作:
使用[
Event] (#create-an-event)创建活动。Register a function to trigger when the
Eventis broadcast by calling theeventobject with the function as an argument.广播
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)
将函数注册到事件#
当您将一个函数注册到某个事件时,当该事件被广播时,该函数将在单独的线程中执行。
Usage:
event(callback, args)
参数 |
描述 |
|---|---|
|
先前创建的事件对象的名称。 |
|
预先定义的函数,将在事件广播时执行。 |
|
可选。要传递给回调函数的参数元组。 |
# 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()
参数 |
描述 |
|---|---|
|
先前创建的事件对象的名称。 |
# 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()
参数 |
描述 |
|---|---|
|
先前创建的事件对象的名称。 |
# 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.")