From f0a7150fada869173f8528161592f9993ee60532 Mon Sep 17 00:00:00 2001
From: fheinrich <fheinrich@techfak.uni-bielefeld.de>
Date: Tue, 5 Mar 2024 11:02:30 +0100
Subject: [PATCH] Cleaned up HTTPErrors

---
 .../configs/study/level1/level1_config.yaml   |  2 +-
 .../configs/study/level2/level2_config.yaml   |  2 +-
 cooperative_cuisine/environment.py            |  3 -
 cooperative_cuisine/game_server.py            |  1 -
 cooperative_cuisine/pygame_2d_vis/gui.py      | 10 +--
 cooperative_cuisine/study_server.py           | 64 ++++++++-----------
 cooperative_cuisine/validation.py             |  1 -
 7 files changed, 34 insertions(+), 49 deletions(-)

diff --git a/cooperative_cuisine/configs/study/level1/level1_config.yaml b/cooperative_cuisine/configs/study/level1/level1_config.yaml
index a11af103..5a5e4b8f 100644
--- a/cooperative_cuisine/configs/study/level1/level1_config.yaml
+++ b/cooperative_cuisine/configs/study/level1/level1_config.yaml
@@ -8,7 +8,7 @@ plates:
 game:
   time_limit_seconds: 300
   undo_dispenser_pickup: true
-  validate_recipes: true
+  validate_recipes: false
 
 meals:
   all: false
diff --git a/cooperative_cuisine/configs/study/level2/level2_config.yaml b/cooperative_cuisine/configs/study/level2/level2_config.yaml
index 585204df..951dc6a4 100644
--- a/cooperative_cuisine/configs/study/level2/level2_config.yaml
+++ b/cooperative_cuisine/configs/study/level2/level2_config.yaml
@@ -5,7 +5,7 @@ plates:
   # range of seconds until the dirty plate arrives.
 
 game:
-  time_limit_seconds: 2
+  time_limit_seconds: 300
   undo_dispenser_pickup: true
   validate_recipes: false
 
diff --git a/cooperative_cuisine/environment.py b/cooperative_cuisine/environment.py
index bee2f95f..23e02704 100644
--- a/cooperative_cuisine/environment.py
+++ b/cooperative_cuisine/environment.py
@@ -224,7 +224,6 @@ class Environment:
             else True
         )
 
-        print("DO VALIDATION", do_validation)
         self.recipe_validation = Validation(
             meals=[m for m in self.item_info.values() if m.type == ItemType.Meal]
             if self.environment_config["meals"]["all"]
@@ -239,11 +238,9 @@ class Environment:
         )
 
         meals_to_be_ordered = self.recipe_validation.validate_environment(self.counters)
-        print("meals_to_be_ordered:", meals_to_be_ordered)
         assert meals_to_be_ordered, "Need possible meals for order generation."
 
         available_meals = {meal: self.item_info[meal] for meal in meals_to_be_ordered}
-
         self.order_manager.set_available_meals(available_meals)
         self.order_manager.create_init_orders(self.env_time)
         self.start_time = self.env_time
diff --git a/cooperative_cuisine/game_server.py b/cooperative_cuisine/game_server.py
index c5d554b1..2d126294 100644
--- a/cooperative_cuisine/game_server.py
+++ b/cooperative_cuisine/game_server.py
@@ -612,7 +612,6 @@ def manage_websocket_message(message: str, client_id: str) -> PlayerRequestResul
     """
     message_dict = json.loads(message)
     request_type = None
-    # ws_message = WebsocketMessage(type=message_dict["type"], player_hash=message_dict["player_hash"])
     try:
         assert "type" in message_dict, "message needs a type"
 
diff --git a/cooperative_cuisine/pygame_2d_vis/gui.py b/cooperative_cuisine/pygame_2d_vis/gui.py
index dd1e4c58..cf6db571 100644
--- a/cooperative_cuisine/pygame_2d_vis/gui.py
+++ b/cooperative_cuisine/pygame_2d_vis/gui.py
@@ -1024,9 +1024,6 @@ class PyGameGUI:
 
         if self.CONNECT_WITH_STUDY_SERVER:
             self.send_level_done()
-        else:
-            pass
-            # self.stop_game_on_server("finished_button_pressed")
         self.disconnect_websockets()
 
         self.update_postgame_screen(self.last_state)
@@ -1380,7 +1377,6 @@ class PyGameGUI:
                 ), "not accepted player"
                 self.websockets[player_id] = websocket
 
-                print("WEBSOCKETS", self.websockets)
             else:
                 # create bots and add bot websockets
                 self.create_and_connect_bot(player_id, player_info)
@@ -1545,7 +1541,11 @@ class PyGameGUI:
             self.get_game_connection(tutorial=False)
         else:
             self.menu_state = MenuStates.Start
-            print("COULD NOT START STUDY; Response:", answer.status_code)
+            print(
+                "COULD NOT START STUDY; Response:",
+                answer.status_code,
+                answer.json()["detail"],
+            )
 
     def send_level_done(self):
         _ = requests.post(f"{self.request_url}/level_done/{self.participant_id}").json()
diff --git a/cooperative_cuisine/study_server.py b/cooperative_cuisine/study_server.py
index 06b7b2cc..31b9d3a0 100644
--- a/cooperative_cuisine/study_server.py
+++ b/cooperative_cuisine/study_server.py
@@ -72,12 +72,6 @@ class StudyConfig(TypedDict):
     num_bots: int
 
 
-# class StudyServerResponse(TypedDict):
-#     status_code: Literal[200] | Literal[409] | Literal[403]
-#     msg: str
-#     data: None | dict[str, PlayerInfo] | dict
-
-
 class StudyState:
     def __init__(self, study_config_path: str | Path, game_url, game_port):
         with open(study_config_path, "r") as file:
@@ -165,6 +159,11 @@ class StudyState:
 
         if env_info.status_code == 403:
             raise ValueError(f"Forbidden Request: {env_info.json()['detail']}")
+        elif env_info.status_code == 500:
+            raise HTTPException(
+                status_code=500,
+                detail=f"Game server crashed.",
+            )
         env_info = env_info.json()
 
         player_info = env_info["player_info"]
@@ -336,28 +335,27 @@ class StudyManager:
             if study.can_add_participants(number_players):
                 player_info = study.add_participant(participant_id, number_players)
                 self.participant_id_to_study_map[participant_id] = study
-                return True, player_info
-        return False, None
+                return player_info
+        raise HTTPException(status_code=409, detail="Could not add participant(s).")
 
-    def player_finished_level(self, participant_id: str) -> bool:
+    def player_finished_level(self, participant_id: str):
         if participant_id in self.participant_id_to_study_map.keys():
             assigned_study = self.participant_id_to_study_map[participant_id]
             assigned_study.player_finished_level(participant_id)
-            return True
         else:
-            return False
+            raise HTTPException(status_code=409, detail="Participant not in any study.")
 
     def get_participant_game_connection(
         self, participant_id: str
-    ) -> Tuple[bool, None | Tuple[PlayerInfo, LevelInfo]]:
-        can_connect = False
+    ) -> Tuple[PlayerInfo, LevelInfo]:
         if participant_id in self.participant_id_to_study_map.keys():
             assigned_study = self.participant_id_to_study_map[participant_id]
             player_info, level_info = assigned_study.get_connection(participant_id)
-            can_connect = True
-            return can_connect, (player_info, level_info)
+            return player_info, level_info
         else:
-            return can_connect, None
+            raise HTTPException(
+                status_code=409, detail="Participant not in this study."
+            )
 
     def set_game_server_url(self, game_host: str, game_port: str):
         self.game_host = game_host
@@ -378,35 +376,22 @@ study_manager = StudyManager()
 @app.post("/start_study/{participant_id}/{number_players}")
 async def start_study(participant_id: str, number_players: int) -> JSONResponse:
     log.debug(f"ADDING PLAYERS: {number_players}")
-    success, player_info = study_manager.add_participant(participant_id, number_players)
-
-    if success:
-        return JSONResponse(content=player_info)
-    else:
-        raise HTTPException(
-            status_code=409, detail="Could not add participant(s), too many players."
-        )
+    player_info = study_manager.add_participant(participant_id, number_players)
+    return JSONResponse(content=player_info)
 
 
 @app.post("/level_done/{participant_id}")
 async def level_done(participant_id: str) -> JSONResponse:
-    ok = study_manager.player_finished_level(participant_id)
-    if ok:
-        return JSONResponse(content="Ok")
-    else:
-        raise HTTPException(status_code=409, detail="Not Ok")
+    study_manager.player_finished_level(participant_id)
+    return JSONResponse(content="Ok")
 
 
 @app.post("/get_game_connection/{participant_id}")
 async def get_game_connection(participant_id: str) -> JSONResponse:
-    can_connect, data = study_manager.get_participant_game_connection(participant_id)
-    if can_connect:
-        player_info, level_info = data
-        return JSONResponse(
-            content={"player_info": player_info, "level_info": level_info}
-        )
-    else:
-        raise HTTPException(status_code=409, detail="No valid game connection.")
+    player_info, level_info = study_manager.get_participant_game_connection(
+        participant_id
+    )
+    return JSONResponse(content={"player_info": player_info, "level_info": level_info})
 
 
 @app.post("/connect_to_tutorial/{participant_id}")
@@ -445,6 +430,11 @@ async def connect_to_tutorial(participant_id: str) -> JSONResponse:
                 status_code=403,
                 detail=f"Forbidden Request: {env_info.json()['detail']}",
             )
+        case 500:
+            raise HTTPException(
+                status_code=500,
+                detail=f"Game server crashed.",
+            )
 
 
 @app.post("/disconnect_from_tutorial/{participant_id}")
diff --git a/cooperative_cuisine/validation.py b/cooperative_cuisine/validation.py
index 0bd0ff2e..ff14a88f 100644
--- a/cooperative_cuisine/validation.py
+++ b/cooperative_cuisine/validation.py
@@ -249,7 +249,6 @@ class Validation:
         return layout_requirements
 
     def validate_environment(self, counters: list[Counter]):
-        print("DO", self.do_validation)
         if self.do_validation:
             graph = self.infer_recipe_graph(self.item_info)
             os.makedirs(ROOT_DIR / "generated", exist_ok=True)
-- 
GitLab