more error correction and stop to hit self
This commit is contained in:
+16
-3
@@ -101,7 +101,7 @@ class AStarSnake(TemplateSnake):
|
|||||||
def heuristic(a, b):
|
def heuristic(a, b):
|
||||||
return abs(a[0] - b[0]) + abs(a[1] - b[1])
|
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 = Queue()
|
||||||
open_set.put(start)
|
open_set.put(start)
|
||||||
came_from = {}
|
came_from = {}
|
||||||
@@ -128,9 +128,16 @@ class AStarSnake(TemplateSnake):
|
|||||||
|
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
try:
|
||||||
nearest_food = min(foods, key=lambda food: heuristic(my_head, (food["x"], food["y"])))
|
nearest_food = min(foods, key=lambda food: heuristic(my_head, (food["x"], food["y"])))
|
||||||
target_position = (nearest_food["x"], nearest_food["y"])
|
target_position = (nearest_food["x"], nearest_food["y"])
|
||||||
move_target = a_star(my_head, target_position)
|
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
|
# Choose the next move based on the path obtained from A* algorithm
|
||||||
if move_target:
|
if move_target:
|
||||||
@@ -148,5 +155,11 @@ class AStarSnake(TemplateSnake):
|
|||||||
return "down"
|
return "down"
|
||||||
|
|
||||||
# If no safe path to food is found, choose a random move
|
# 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})
|
random_move = random.choice(["up", "down", "left", "right"])
|
||||||
return 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
|
||||||
|
|||||||
Reference in New Issue
Block a user