Timer#
Mit Timern kannst du Ereignisse zeitgesteuert ausführen.
This means that an action is not started immediately, but with a delay of milliseconds or seconds.
Timers are useful if you want an action to take place only after a certain period of time, for example.
Bemerkung
Python provides the time.sleep(...)
function in the time
library to create delays. However, you should not use this method as it leads to global delays and can cause unwanted side effects.
Starten Sie einen Timer#
To start a timer, you can use the following example:
from miniworlds import ActionTimer
[...]
ActionTimer(24, player.move)
Erklärung#
After 24 frames, the timer is triggered.
The method
player.move
is then executed.
Different types of timers#
There are different types of timers that can be used depending on the application:
Aktions-Timer#
The ActionTimer executes a method after a specified time and then automatically removes itself. It is suitable for actions that should be executed once after a delay.
ActionTimer(24, player.move, None)
In this example, the move
function of the player
object is executed once after 24 frames.
LoopActionTimer#
The LoopActionTimer works similarly to the ActionTimer, but repeats the action at regular intervals. This timer is ideal for recurring actions.
LoopActionTimer(24, player.move)
In this case, the move
method of the player
object is executed every 24 frames.
Um einen LoopActionTimer zu stoppen, kannst du ihn wie folgt entfernen:
loopactiontimer = LoopActionTimer(24, player.move)
...
loopactiontimer.unregister() # Entfernt den LoopActionTimer
Timer mit Ereignissen verknüpfen#
Ähnlich wie bei Sensoren kannst du Timer so konfigurieren, dass Methoden auf bestimmte Timer-Ereignisse reagieren. Dazu registrierst du Methoden, die bei einem Timer-Ereignis ausgeführt werden sollen.
An example of such a method looks as follows:
@timer(frames=24)
def moving():
player.move()
In this case, the method moving
is called after 24 frames and executes the action player.move()
.
To register a LoopTimer that runs regularly, you can use the following example:
@loop(frames=48)
def moving():
player.turn_left()
player.move(2)
Here, the moving
method is executed repeatedly every 48 frames, causing the actor to turn and move to the left.