69 lines
1.6 KiB
Python

import utils
from maze_common import MOVEMENTS
from maze_common import spawn_maze
def cmp_function(lhs, rhs):
treasure_x, treasure_y = measure()
lhs_heuristic = abs(lhs[0] - treasure_x) + abs(lhs[1] - treasure_y)
rhs_heuristic = abs(rhs[0] - treasure_x) + abs(rhs[1] - treasure_y)
return lhs_heuristic < rhs_heuristic
def run(size):
if (get_world_size() != size):
set_world_size(size)
if not spawn_maze():
return False
stack = []
visited = {}
treasure_found = False
visited[(get_pos_x(),get_pos_y())] = (get_pos_x(), get_pos_y())
while not treasure_found:
if get_entity_type() == Entities.Treasure:
treasure_found = True
continue
x = get_pos_x()
y = get_pos_y()
possible_moves = []
if (x - 1, y) not in visited and can_move(West):
possible_moves.append((x - 1, y))
if (x + 1, y) not in visited and can_move(East):
possible_moves.append((x + 1, y))
if (x, y - 1) not in visited and can_move(South):
possible_moves.append((x, y - 1))
if (x, y + 1) not in visited and can_move(North):
possible_moves.append((x, y + 1))
if (len(possible_moves) == 0):
hx, hy = utils.list_back(stack)
stack.pop()
move(MOVEMENTS[(hx - x, hy - y)])
continue
utils.sort(possible_moves, cmp_function)
(nx, ny) = utils.list_back(possible_moves)
stack.append((x, y))
visited[(nx, ny)] = (x, y)
move(MOVEMENTS[(nx - x, ny - y)])
harvest()
return True