From 1853160231f82f479adeb4d53c913b6b4bc7a3b4 Mon Sep 17 00:00:00 2001
From: fheinrich <fheinrich@techfak.uni-bielefeld.de>
Date: Fri, 8 Mar 2024 16:11:12 +0100
Subject: [PATCH] Stylechecks, docstrings

---
 cooperative_cuisine/counters.py    | 15 +++++++++------
 cooperative_cuisine/environment.py |  8 +++++---
 cooperative_cuisine/game_server.py | 15 +++++++++------
 cooperative_cuisine/hooks.py       |  2 +-
 cooperative_cuisine/recording.py   | 19 ++++++++++++-------
 5 files changed, 36 insertions(+), 23 deletions(-)

diff --git a/cooperative_cuisine/counters.py b/cooperative_cuisine/counters.py
index a0a495a2..991074a3 100644
--- a/cooperative_cuisine/counters.py
+++ b/cooperative_cuisine/counters.py
@@ -298,13 +298,14 @@ class Counter:
         return False
 
     def do_hand_free_interaction(
-        self, passed_time: timedelta, now: datetime, player_name: str
+        self, passed_time: timedelta, now: datetime, player: str
     ):
         """Called by environment step function for time progression.
 
         Args:
             passed_time: the time passed since the last progress call
             now: the current env time. **Not the same as `datetime.now`**.
+            player: Name of the player doing the interaction.
         """
         ...
 
@@ -351,13 +352,14 @@ class CuttingBoard(Counter):
         super().__init__(**kwargs)
 
     def do_hand_free_interaction(
-        self, passed_time: timedelta, now: datetime, player_name: str
+        self, passed_time: timedelta, now: datetime, player: str
     ):
         """Called by environment step function for time progression.
 
         Args:
             passed_time: the time passed since the last progress call
             now: the current env time. **Not the same as `datetime.now`**.
+            player: Name of the player doing the interaction.
 
         Checks if the item on the board is in the allowed transitions via a Cutting board. Pass the progress call to
         the item on the board. If the progress on the item reaches 100% it changes the name of the item based on the
@@ -393,7 +395,7 @@ class CuttingBoard(Counter):
                 self.occupied_by.name = self.inverted_transition_dict[
                     self.occupied_by.name
                 ].name
-                self.hook(CUTTING_BOARD_100, counter=self, player_name=player_name)
+                self.hook(CUTTING_BOARD_100, counter=self, player=player)
 
 
 class ServingWindow(Counter):
@@ -551,7 +553,8 @@ class PlateDispenser(Counter):
     """At the moment, one and only one plate dispenser must exist in an environment, because only at one place the dirty
     plates should arrive.
 
-    How many plates should exist at the start of the level on the plate dispenser is defined in the `environment_config.yml`:
+    How many plates should exist at the start of the level on the
+    plate dispenser is defined in the `environment_config.yml`:
     ```yaml
     plates:
       clean_plates: 1
@@ -836,7 +839,7 @@ class Sink(Counter):
         return len(self.occupied_by) != 0
 
     def do_hand_free_interaction(
-        self, passed_time: timedelta, now: datetime, player_name: str
+        self, passed_time: timedelta, now: datetime, player: str
     ):
         if (
             self.occupied
@@ -868,7 +871,7 @@ class Sink(Counter):
                         equipment=self.__class__.__name__, percent=percent
                     )
                     if self.occupied_by[-1].progress_percentage == 1.0:
-                        self.hook(PLATE_CLEANED, counter=self, player_name=player_name)
+                        self.hook(PLATE_CLEANED, counter=self, player=player)
                         self.occupied_by[-1].reset()
                         self.occupied_by[-1].name = name
                         plate = self.occupied_by.pop()
diff --git a/cooperative_cuisine/environment.py b/cooperative_cuisine/environment.py
index cadcac0a..a98b6c71 100644
--- a/cooperative_cuisine/environment.py
+++ b/cooperative_cuisine/environment.py
@@ -427,7 +427,7 @@ class Environment:
             player.update_facing_point()
 
         self.movement.set_collision_arrays(len(self.players))
-        self.hook(PLAYER_ADDED, player_name=player_name, pos=pos)
+        self.hook(PLAYER_ADDED, player=player, pos=pos)
 
     def step(self, passed_time: timedelta):
         """Performs a step of the environment. Affects time based events such as cooking or cutting things, orders
@@ -533,8 +533,10 @@ class Environment:
         """Registers a callback function for a given hook reference.
 
         Args:
-            hook_ref (str | list[str]): The reference to the hook or hooks for which the callback should be registered. It can be a single string or a list of strings.
-            callback (Callable): The callback function to be registered for the specified hook(s). The function should accept the necessary parameters and perform the desired actions.
+            hook_ref (str | list[str]): The reference to the hook or hooks for which the callback should be registered.
+            It can be a single string or a list of strings.
+            callback (Callable): The callback function to be registered for the specified hook(s).
+            The function should accept the necessary parameters and perform the desired actions.
 
         """
         self.hook.register_callback(hook_ref, callback)
diff --git a/cooperative_cuisine/game_server.py b/cooperative_cuisine/game_server.py
index 6cf18d8f..17e4de5a 100644
--- a/cooperative_cuisine/game_server.py
+++ b/cooperative_cuisine/game_server.py
@@ -93,7 +93,7 @@ class EnvironmentStatus(Enum):
     RUNNING = "running"
     """The environment is running."""
     STOPPED = "stopped"
-    """The environement is stopped."""
+    """The environment is stopped."""
 
 
 @dataclasses.dataclass
@@ -312,7 +312,7 @@ class EnvironmentHandler:
         Args:
             manager_id (str): The ID of the manager that manages the environment.
             env_id (str): The ID of the environment.
-            reason (str): The reason for unpausing the environment.
+            reason (str): The reason for un-pausing the environment.
         """
         if (
             manager_id in self.manager_envs
@@ -512,7 +512,8 @@ class EnvironmentHandler:
     def is_known_client_id(self, client_id: str) -> bool:
         """Check if a client ID is known.
 
-        Client IDs are generated by the server for players to connect to a websocket. Therefore, unknown IDs are ignored.
+        Client IDs are generated by the server for players to connect to a websocket.
+        Therefore, unknown IDs are ignored.
 
         Args:
             client_id (str): The client ID to be checked.
@@ -526,7 +527,8 @@ class EnvironmentHandler:
         """Pass an action of a player to the environment.
 
         Args:
-            player_hash (str): The hash that allows access to the player data (should only know the player client and not other players).
+            player_hash (str): The hash that allows access to the player data
+            (should only know the player client and not other players).
             action (Action): The action to be performed.
 
         Returns:
@@ -772,7 +774,7 @@ async def stop_env(manage_env: ManageEnv) -> str:
 
 @app.websocket("/ws/player/{client_id}")
 async def websocket_player_endpoint(websocket: WebSocket, client_id: str):
-    """The method that recives messages from the websocket of a player and sends the results back to the client.
+    """The method that receives messages from the websocket of a player and sends the results back to the client.
 
     Args:
         websocket (WebSocket): The WebSocket connection object.
@@ -815,7 +817,8 @@ if __name__ == "__main__":
     parser = argparse.ArgumentParser(
         prog="Cooperative Cuisine Game Server",
         description="Game Engine Server: Starts overcooked game engine server.",
-        epilog="For further information, see https://scs.pages.ub.uni-bielefeld.de/cocosy/overcooked-simulator/cooperative_cuisine.html",
+        epilog="For further information, see "
+               "https://scs.pages.ub.uni-bielefeld.de/cocosy/overcooked-simulator/cooperative_cuisine.html",
     )
 
     url_and_port_arguments(parser)
diff --git a/cooperative_cuisine/hooks.py b/cooperative_cuisine/hooks.py
index 601a2b20..2c9f4900 100644
--- a/cooperative_cuisine/hooks.py
+++ b/cooperative_cuisine/hooks.py
@@ -43,7 +43,7 @@ POST_PERFORM_ACTION = "post_perform_action"
 # TODO Pre and Post Perform Movement
 
 PLAYER_ADDED = "player_added"
-"""Called after a player has been added. Kwargs: `player_name` and `pos`."""
+"""Called after a player has been added. Kwargs: `player` and `pos`."""
 
 GAME_ENDED_STEP = "game_ended_step"
 
diff --git a/cooperative_cuisine/recording.py b/cooperative_cuisine/recording.py
index ca6788d2..9f5984af 100644
--- a/cooperative_cuisine/recording.py
+++ b/cooperative_cuisine/recording.py
@@ -135,6 +135,13 @@ class FileRecorder(HookCallbackClass):
 
 
 def print_recorded_events_human_readable(jsonl_path: Path):
+    """This function prints a game_event recording in human-readable form.
+
+    Args:
+        jsonl_path: Path to the file with recorded game events.
+
+    """
+
     def stringify_item(item):
         if isinstance(item, float):
             return str(item)
@@ -194,11 +201,11 @@ def print_recorded_events_human_readable(jsonl_path: Path):
                     case "new_orders":
                         orders = [f"Order({o['meal']})" for o in record[dict_key]]
                         record[dict_key] = orders
-                    case other:
+                    case _:
                         try:
                             record[dict_key] = stringify_item(record[dict_key])
-                        except KeyError as e:
-                            pass
+                        except KeyError | TypeError as e:
+                            print(hook, dict_key, record[dict_key], type(e), e)
 
             if hook in string_templates.keys():
                 string_template = Template(string_templates[hook])
@@ -210,7 +217,5 @@ def print_recorded_events_human_readable(jsonl_path: Path):
 
 
 if __name__ == "__main__":
-    jsonl_path: Path = Path(
-        "/Users/fheinrich/Library/Logs/cooperative_cuisine/e8b0551442934324bd3204c46379ebe5/game_events.jsonl"
-    )
-    print_recorded_events_human_readable(jsonl_path)
+    json_lines_path: Path = Path("PATH/TO//game_events.jsonl")
+    print_recorded_events_human_readable(json_lines_path)
-- 
GitLab