イベント#

導入#

イベントを使用すると、関数を並列実行できます。関数を順番に呼び出す代わりに、複数の関数をイベントに登録して、それらを一度にすべて実行できます。登録された各関数はそれぞれ独自のスレッドで実行されるため、ロボットは走行中に画面に値を表示するなど、複数のタスクを同時に実行できます。

イベントを作成して使用するには、以下の手順を順番に実行してください。

  1. Event を使用してイベントを作成します。

  2. 関数を引数として Event オブジェクト を呼び出すことにより、 event がブロードキャストされたときにトリガーされる関数を登録します。

  3. Broadcast an Event:

    • broadcast – イベント オブジェクトに登録されているすべての関数を同時に実行するようにトリガーします。

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

パラメータ

説明

event

以前に作成されたイベントオブジェクトの名前。

callback

イベントがブロードキャストされた際に実行される、事前に定義された関数。

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