def bfs_agent(self,env):
"""用 BFS 找到蛇头到食物的最短路径,返回第一个动作"""
head = (int(env.snake_x), int(env.snake_y))
food = (int(env.food_x), int(env.food_y))
snake_body = set(map(tuple, env.snake_list)) # 把蛇身体当成障碍
directions = {
0: (0, -env.snake_block), # up
1: (0, env.snake_block), # down
2: (-env.snake_block, 0), # left
3: (env.snake_block, 0) # right
}
queue = deque([(head, [])])
visited = {head}
while queue:
(x, y), path = queue.popleft()
# 找到食物,返回路径的第一个动作
if (x, y) == food:
return path[0] if path else random.choice([0, 1, 2, 3])
for action, (dx, dy) in directions.items():
nx, ny = x + dx, y + dy
# 边界检查
if 0 <= nx < env.window_width and 0 <= ny < env.window_height:
if (nx, ny) not in snake_body and (nx, ny) not in visited:
visited.add((nx, ny))
queue.append(((nx, ny), path + [action]))
# 如果没有路径,随机走一步
return random.choice([0, 1, 2, 3])