-
Florian Schröder authored
Merge remote-tracking branch 'origin/dev' into 115-remove-repitition-of-hook-callback-class-in-env-config
Florian Schröder authoredMerge remote-tracking branch 'origin/dev' into 115-remove-repitition-of-hook-callback-class-in-env-config
info_msg.py 3.26 KiB
"""Based on hooks, text-based info msgs can be displayed.
```yaml
hook_callbacks:
info_msg:
hooks: [ cutting_board_100 ]
callback_class: !!python/name:cooperative_cuisine.info_msg.InfoMsgManager ''
callback_class_kwargs:
msg: Glückwunsch du hast was geschnitten!
fire_msg:
hooks: [ new_fire ]
callback_class: !!python/name:cooperative_cuisine.info_msg.InfoMsgManager ''
callback_class_kwargs:
msg: Feuer, Feuer, Feuer
level: Warning
```
"""
from datetime import timedelta
from cooperative_cuisine.environment import Environment
from cooperative_cuisine.hooks import HookCallbackClass
class InfoMsgManager(HookCallbackClass):
"""
Class for managing info messages in an environment.
This class inherits from the `HookCallbackClass` class.
Attributes:
msg (str): The message to be displayed.
duration (datetime.timedelta): The duration for which the message should be displayed.
level (str): The level of the message.
Methods:
__init__(name, env, msg, duration, level, **kwargs): Initializes an instance of InfoMsgManager.
__call__(hook_ref, env, **kwargs): Adds the message to the info messages list for each player in the environment.
remove_old_msgs(env): Removes old messages from the environment.
"""
def __init__(
self,
name: str,
env: Environment,
msg: str,
duration: int = 5,
level: str = "Normal",
**kwargs
):
"""Constructor of InfoMsgManager.
Args:
name (str): The name of the instance.
env (Environment): The environment in which the instance exists.
msg (str): The message associated with the instance.
duration (int, optional): The duration of the instance (in seconds). Defaults to 5.
level (str, optional): The level of the instance. Defaults to "Normal".
**kwargs: Additional keyword arguments.
"""
super().__init__(name, env, **kwargs)
self.msg: str = msg
"""Text message to display when the hook is called."""
self.duration: timedelta = timedelta(seconds=duration)
"""Duration of the msg to display."""
self.level: str = level
"""Level of the msg, e.g., "Normal", "Warning", "Success"."""
def __call__(self, hook_ref: str, env: Environment, **kwargs):
for player_id in env.players:
env.info_msgs_per_player[player_id].append(
{
"msg": self.msg,
"start_time": env.env_time,
"end_time": env.env_time + self.duration,
"level": self.level,
}
)
self.remove_old_msgs(env)
@staticmethod
def remove_old_msgs(env: Environment):
"""
Removes old messages from the environment.
Args:
env (Environment): The environment object containing the messages.
"""
for player_id, msgs in env.info_msgs_per_player.items():
delete_msgs = []
for idx, msg in enumerate(msgs):
if msg["end_time"] <= env.env_time:
delete_msgs.append(idx)
for idx in reversed(delete_msgs):
msgs.pop(idx)