From 3c7946382c87d3c252a5820889f1014963621c81 Mon Sep 17 00:00:00 2001 From: Daniel Dolezal Date: Fri, 12 Apr 2024 12:27:11 +0200 Subject: [PATCH] more error correction and stop to hit self --- snakes/AStarSnake.py | 25 +++++++++++++++++++------ 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/snakes/AStarSnake.py b/snakes/AStarSnake.py index 9aaacc1..a09d6a8 100644 --- a/snakes/AStarSnake.py +++ b/snakes/AStarSnake.py @@ -101,7 +101,7 @@ class AStarSnake(TemplateSnake): def heuristic(a, b): return abs(a[0] - b[0]) + abs(a[1] - b[1]) - def a_star(start, goal): + def a_star(start, goal:set=()): open_set = Queue() open_set.put(start) came_from = {} @@ -128,9 +128,16 @@ class AStarSnake(TemplateSnake): return None - nearest_food = min(foods, key=lambda food: heuristic(my_head, (food["x"], food["y"]))) - target_position = (nearest_food["x"], nearest_food["y"]) - move_target = a_star(my_head, target_position) + try: + nearest_food = min(foods, key=lambda food: heuristic(my_head, (food["x"], food["y"]))) + target_position = (nearest_food["x"], nearest_food["y"]) + move_target = a_star(my_head, target_position) + except ValueError: + # TODO: What to do when no food is available? + # - Avoid own body and other snakes + # - Flut fill? + move_target = a_star(my_head, safe_cells) + print(move_target) # Choose the next move based on the path obtained from A* algorithm if move_target: @@ -148,5 +155,11 @@ class AStarSnake(TemplateSnake): return "down" # If no safe path to food is found, choose a random move - self.add_to_history({"my_head": my_head, "my_body": tuple(my_body), "target": move_target, "target_position": target_position, "nearest_food": nearest_food}) - return random.choice(["up", "down", "left", "right"]) + random_move = random.choice(["up", "down", "left", "right"]) + + try: + self.add_to_history({"my_head": my_head, "my_body": tuple(my_body), "target": move_target, "target_position": target_position, "nearest_food": nearest_food, "random_move": random_move}) + except UnboundLocalError: + self.add_to_history({"my_head": my_head, "my_body": tuple(my_body), "target": move_target, "random_move": random_move}) + + return random_move