使用python实现A*算法,要求可以使用鼠标点击方块选择起点、终点,障碍物是随机生成的

时间: 2024-03-08 14:51:22 浏览: 19
好的,我可以为您提供一个基本的 A*算法的实现,并添加鼠标交互和随机障碍物的功能。在代码中,我将使用 Pygame 库来处理鼠标事件和绘制方块。 首先,需要安装 Pygame 库。可以使用以下命令在终端中安装: ``` pip install pygame ``` 然后,我们可以开始编写代码。下面是完整的代码: ```python import pygame from queue import PriorityQueue import random # 设置棋盘大小和方块大小 WIDTH = 800 WIN = pygame.display.set_mode((WIDTH, WIDTH)) pygame.display.set_caption("A* Path Finding Algorithm") BLOCK_SIZE = 20 # 定义颜色 WHITE = (255, 255, 255) BLACK = (0, 0, 0) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) YELLOW = (255, 255, 0) # 定义方块类 class Block: def __init__(self, row, col): self.row = row self.col = col self.x = row * BLOCK_SIZE self.y = col * BLOCK_SIZE self.color = WHITE self.neighbors = [] def get_pos(self): return self.row, self.col def is_barrier(self): return self.color == BLACK def reset(self): self.color = WHITE def make_start(self): self.color = GREEN def make_barrier(self): self.color = BLACK def make_end(self): self.color = RED def make_path(self): self.color = YELLOW def draw(self): pygame.draw.rect(WIN, self.color, (self.x, self.y, BLOCK_SIZE, BLOCK_SIZE)) # 添加邻居 def add_neighbors(self, grid): if self.row < len(grid) - 1 and not grid[self.row + 1][self.col].is_barrier(): # 下 self.neighbors.append(grid[self.row + 1][self.col]) if self.row > 0 and not grid[self.row - 1][self.col].is_barrier(): # 上 self.neighbors.append(grid[self.row - 1][self.col]) if self.col < len(grid[0]) - 1 and not grid[self.row][self.col + 1].is_barrier(): # 右 self.neighbors.append(grid[self.row][self.col + 1]) if self.col > 0 and not grid[self.row][self.col - 1].is_barrier(): # 左 self.neighbors.append(grid[self.row][self.col - 1]) def __lt__(self, other): return False # 定义启发函数 def h(node1, node2): return abs(node1.row - node2.row) + abs(node1.col - node2.col) # 定义算法函数 def a_star_algorithm(grid, start, end): count = 0 open_set = PriorityQueue() open_set.put((0, count, start)) came_from = {} g_score = {block: float("inf") for row in grid for block in row} g_score[start] = 0 f_score = {block: float("inf") for row in grid for block in row} f_score[start] = h(start, end) open_set_hash = {start} while not open_set.empty(): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() current = open_set.get()[2] open_set_hash.remove(current) if current == end: reconstruct_path(came_from, end) end.make_end() return True for neighbor in current.neighbors: temp_g_score = g_score[current] + 1 if temp_g_score < g_score[neighbor]: came_from[neighbor] = current g_score[neighbor] = temp_g_score f_score[neighbor] = temp_g_score + h(neighbor, end) if neighbor not in open_set_hash: count += 1 open_set.put((f_score[neighbor], count, neighbor)) open_set_hash.add(neighbor) neighbor.color = BLUE draw_grid(grid) if current != start: current.color = YELLOW end.color = RED pygame.display.update() if start in open_set_hash: start.color = GREEN else: start.color = BLACK return False # 重构路径 def reconstruct_path(came_from, current): while current in came_from: current = came_from[current] current.make_path() # 绘制网格 def draw_grid(grid): for row in grid: for block in row: block.draw() for i in range(len(grid)): pygame.draw.line(WIN, BLACK, (0, i * BLOCK_SIZE), (WIDTH, i * BLOCK_SIZE)) for j in range(len(grid[0])): pygame.draw.line(WIN, BLACK, (j * BLOCK_SIZE, 0), (j * BLOCK_SIZE, WIDTH)) pygame.display.update() # 创建随机障碍物 def create_barriers(grid): for i in range(len(grid)): for j in range(len(grid[0])): if random.randint(0, 3) == 0: grid[i][j].make_barrier() # 初始化棋盘 def init_grid(): grid = [] for i in range(int(WIDTH / BLOCK_SIZE)): row = [] for j in range(int(WIDTH / BLOCK_SIZE)): block = Block(i, j) row.append(block) grid.append(row) for i in range(len(grid)): for j in range(len(grid[0])): grid[i][j].add_neighbors(grid) return grid # 主函数 def main(): run = True started = False grid = init_grid() start = None end = None while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if started: continue if pygame.mouse.get_pressed()[0]: # 鼠标左键按下 pos = pygame.mouse.get_pos() row = pos[0] // BLOCK_SIZE col = pos[1] // BLOCK_SIZE block = grid[row][col] if not start and block != end: start = block start.make_start() elif not end and block != start: end = block end.make_end() elif block != start and block != end: block.make_barrier() elif pygame.mouse.get_pressed()[2]: # 鼠标右键按下 pos = pygame.mouse.get_pos() row = pos[0] // BLOCK_SIZE col = pos[1] // BLOCK_SIZE block = grid[row][col] block.reset() if block == start: start = None elif block == end: end = None if event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE and not started: for row in grid: for block in row: block.add_neighbors(grid) create_barriers(grid) a_star_algorithm(grid, start, end) pygame.quit() if __name__ == "__main__": main() ``` 运行代码后,您将看到一个棋盘,您可以使用鼠标左键选择起点、终点,使用鼠标右键删除方块,然后按下空格键运行 A*算法。障碍物将自动随机分布在棋盘上。当算法运行时,您将看到蓝色方块表示算法正在搜索的路径,黄色方块表示搜索到的路径,红色方块表示终点,绿色方块表示起点。 希望这能帮助您开始实现 A*算法。

相关推荐

最新推荐

recommend-type

Python3 A*寻路算法实现方式

今天小编就为大家分享一篇Python3 A*寻路算法实现方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

python 实现红包随机生成算法的简单实例

下面小编就为大家带来一篇python 实现红包随机生成算法的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
recommend-type

python实现随机漫步算法

主要为大家详细介绍了python实现随机漫步算法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
recommend-type

Python实现windows下模拟按键和鼠标点击的方法

主要介绍了Python实现windows下模拟按键和鼠标点击的方法,涉及Python模拟实现鼠标及键盘事件的技巧,具有一定参考借鉴价值,需要的朋友可以参考下
recommend-type

使用Python脚本生成随机IP的简单方法

主要介绍了使用Python脚本生成随机IP的简单方法,并且可以自己设定IP数值范围,需要的朋友可以参考下
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

【实战演练】MATLAB用遗传算法改进粒子群GA-PSO算法

![MATLAB智能算法合集](https://static.fuxi.netease.com/fuxi-official/web/20221101/83f465753fd49c41536a5640367d4340.jpg) # 2.1 遗传算法的原理和实现 遗传算法(GA)是一种受生物进化过程启发的优化算法。它通过模拟自然选择和遗传机制来搜索最优解。 **2.1.1 遗传算法的编码和解码** 编码是将问题空间中的解表示为二进制字符串或其他数据结构的过程。解码是将编码的解转换为问题空间中的实际解的过程。常见的编码方法包括二进制编码、实数编码和树形编码。 **2.1.2 遗传算法的交叉和
recommend-type

openstack的20种接口有哪些

以下是OpenStack的20种API接口: 1. Identity (Keystone) API 2. Compute (Nova) API 3. Networking (Neutron) API 4. Block Storage (Cinder) API 5. Object Storage (Swift) API 6. Image (Glance) API 7. Telemetry (Ceilometer) API 8. Orchestration (Heat) API 9. Database (Trove) API 10. Bare Metal (Ironic) API 11. DNS
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。