more error correction and stop to hit self

This commit is contained in:
2024-04-12 12:27:11 +02:00
parent e9a6e106c8
commit 3c7946382c
+16 -3
View File
@@ -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
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