python
import tkinter as tk
from queue import PriorityQueue
# 定义地图大小
MAP_WIDTH = 20
MAP_HEIGHT = 20
# 定义地图元素
EMPTY = 0
OBSTACLE = 1
ANT_HILL = 2
FOOD = 3
# 定义颜色映射
COLORS = {
EMPTY: "white",
OBSTACLE: "black",
ANT_HILL: "blue",
FOOD: "green",
"PATH": "yellow"
}
# 初始化地图
def create_map():
return [
[EMPTY for _ in range(MAP_WIDTH)]
for _ in range(MAP_HEIGHT)
]
# A* 算法实现
def a_star_search(grid, start, goal):
def heuristic(a, b):
return abs(a[0] - b[0]) + abs(a[1] - b[1])
open_set = PriorityQueue()
open_set.put((0, start))
came_from = {}
g_score = {start: 0}
f_score = {start: heuristic(start, goal)}
while not open_set.empty():
_, current = open_set.get()
if current == goal:
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1]
for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
neighbor = (current[0] + dx, current[1] + dy)
if (
0 <= neighbor[0] < MAP_HEIGHT and
0 <= neighbor[1] < MAP_WIDTH and
grid[neighbor[0]][neighbor[1]] != OBSTACLE
):
tentative_g_score = g_score[current] + 1
if neighbor not in g_score or tentative_g_score < g_score[neighbor]:
came_from[neighbor] = current
g_score[neighbor] = tentative_g_score
f_score[neighbor] = tentative_g_score + heuristic(neighbor, goal)
open_set.put((f_score[neighbor], neighbor))
return None
# 可视化类
class AntSimulation:
def __init__(self, root):
self.root = root
self.canvas = tk.Canvas(root, width=400, height=400)
self.canvas.pack()
self.grid = create_map()
self.ant_position = (0, 0)
self.food_position = (MAP_HEIGHT - 1, MAP_WIDTH - 1)
self.grid[self.ant_position[0]][self.ant_position[1]] = ANT_HILL
self.grid[self.food_position[0]][self.food_position[1]] = FOOD
# 添加一些障碍物
self.grid[5][5] = OBSTACLE
self.grid[5][6] = OBSTACLE
self.grid[6][5] = OBSTACLE
self.draw_grid()
self.find_path()
def draw_grid(self):
cell_width = 400 // MAP_WIDTH
cell_height = 400 // MAP_HEIGHT
for row in range(MAP_HEIGHT):
for col in range(MAP_WIDTH):
x1 = col * cell_width
y1 = row * cell_height
x2 = x1 + cell_width
y2 = y1 + cell_height
color = COLORS[self.grid[row][col]]
self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline="gray")
def find_path(self):
path = a_star_search(self.grid, self.ant_position, self.food_position)
if path:
for step in path:
if step != self.ant_position and step != self.food_position:
self.grid[step[0]][step[1]] = "PATH"
self.draw_grid()
# 主函数
if __name__ == "__main__":
root = tk.Tk()
root.title("蚂蚁找食物模拟")
app = AntSimulation(root)
root.mainloop()