Python 绘制迷宫游戏,自带最优解路线

devtools/2025/3/5 5:27:07/

1、需要安装pygame
2、上下左右移动,空格实现物体所在位置到终点的路线,会有虚线绘制。
在这里插入图片描述

import pygame
import random
import math# 迷宫单元格类
class Cell:def __init__(self, x, y):self.x = xself.y = yself.walls = {'top': True, 'right': True, 'bottom': True, 'left': True}self.visited = Falseself.is_obstacle = Falsedef draw(self, screen, cell_size):x = self.x * cell_sizey = self.y * cell_sizeif self.walls['top']:pygame.draw.line(screen, (0, 0, 0), (x, y), (x + cell_size, y), 2)if self.walls['right']:pygame.draw.line(screen, (0, 0, 0), (x + cell_size, y), (x + cell_size, y + cell_size), 2)if self.walls['bottom']:pygame.draw.line(screen, (0, 0, 0), (x + cell_size, y + cell_size), (x, y + cell_size), 2)if self.walls['left']:pygame.draw.line(screen, (0, 0, 0), (x, y + cell_size), (x, y), 2)if self.is_obstacle:pygame.draw.rect(screen, (128, 128, 128), (x, y, cell_size, cell_size))def check_neighbors(self, grid, cols, rows):neighbors = []if self.x > 0:left = grid[self.y][self.x - 1]if not left.visited:neighbors.append(left)if self.x < cols - 1:right = grid[self.y][self.x + 1]if not right.visited:neighbors.append(right)if self.y > 0:top = grid[self.y - 1][self.x]if not top.visited:neighbors.append(top)if self.y < rows - 1:bottom = grid[self.y + 1][self.x]if not bottom.visited:neighbors.append(bottom)if neighbors:return random.choice(neighbors)else:return None# 移除两个单元格之间的墙
def remove_walls(current, next_cell):dx = current.x - next_cell.xif dx == 1:current.walls['left'] = Falsenext_cell.walls['right'] = Falseelif dx == -1:current.walls['right'] = Falsenext_cell.walls['left'] = Falsedy = current.y - next_cell.yif dy == 1:current.walls['top'] = Falsenext_cell.walls['bottom'] = Falseelif dy == -1:current.walls['bottom'] = Falsenext_cell.walls['top'] = False# 生成迷宫
def generate_maze(grid, cols, rows):stack = []current = grid[0][0]current.visited = Truestack.append(current)while stack:current = stack[-1]next_cell = current.check_neighbors(grid, cols, rows)if next_cell:next_cell.visited = Truestack.append(next_cell)remove_walls(current, next_cell)else:stack.pop()# 随机添加障碍物
def add_obstacles(grid, cols, rows, obstacle_ratio=0.3):obstacle_cells = []num_obstacles = int(cols * rows * obstacle_ratio)while len(obstacle_cells) < num_obstacles:x = random.randint(0, cols - 1)y = random.randint(0, rows - 1)if (x, y) not in [(0, 0), (cols - 1, rows - 1)] and not grid[y][x].is_obstacle:grid[y][x].is_obstacle = Trueobstacle_cells.append((x, y))return obstacle_cells# 检查从起点到终点是否有路径
def has_path(grid, start, end):path = find_path(grid, start, end)return bool(path)# 移除障碍物直到有路径
def ensure_path_exists(grid, start, end, obstacle_cells):random.shuffle(obstacle_cells)while not has_path(grid, start, end) and obstacle_cells:x, y = obstacle_cells.pop()grid[y][x].is_obstacle = False# 绘制迷宫
def draw_maze(screen, grid, cell_size, cols, rows):for i in range(rows):for j in range(cols):grid[i][j].draw(screen, cell_size)# 绘制起点和终点
def draw_start_end(screen, cell_size, start, end):start_x = start[0] * cell_size + cell_size // 2start_y = start[1] * cell_size + cell_size // 2end_x = end[0] * cell_size + cell_size // 2end_y = end[1] * cell_size + cell_size // 2pygame.draw.circle(screen, (0, 255, 0), (start_x, start_y), cell_size // 3)pygame.draw.circle(screen, (255, 0, 0), (end_x, end_y), cell_size // 3)# 绘制移动的物体
def draw_player(screen, cell_size, player_pos):player_x = player_pos[0] * cell_size + cell_size // 2player_y = player_pos[1] * cell_size + cell_size // 2pygame.draw.circle(screen, (0, 0, 255), (player_x, player_y), cell_size // 3)# 检查是否可以移动
def can_move(grid, player_pos, direction):x, y = player_posif direction == 'up':return y > 0 and not grid[y][x].walls['top'] and not grid[y - 1][x].is_obstacleelif direction == 'down':return y < len(grid) - 1 and not grid[y][x].walls['bottom'] and not grid[y + 1][x].is_obstacleelif direction == 'left':return x > 0 and not grid[y][x].walls['left'] and not grid[y][x - 1].is_obstacleelif direction == 'right':return x < len(grid[0]) - 1 and not grid[y][x].walls['right'] and not grid[y][x + 1].is_obstacle# 广度优先搜索找到最优路径
def find_path(grid, start, end):queue = [(start, [start])]visited = set()while queue:(x, y), path = queue.pop(0)if (x, y) == end:return pathif (x, y) not in visited:visited.add((x, y))if can_move(grid, (x, y), 'up'):new_path = list(path)new_path.append((x, y - 1))queue.append(((x, y - 1), new_path))if can_move(grid, (x, y), 'down'):new_path = list(path)new_path.append((x, y + 1))queue.append(((x, y + 1), new_path))if can_move(grid, (x, y), 'left'):new_path = list(path)new_path.append((x - 1, y))queue.append(((x - 1, y), new_path))if can_move(grid, (x, y), 'right'):new_path = list(path)new_path.append((x + 1, y))queue.append(((x + 1, y), new_path))return []# 绘制虚线
def draw_dashed_line(screen, color, start_pos, end_pos, dash_length=5):dx = end_pos[0] - start_pos[0]dy = end_pos[1] - start_pos[1]distance = math.sqrt(dx ** 2 + dy ** 2)num_dashes = int(distance / dash_length)for i in range(num_dashes):if i % 2 == 0:start = (start_pos[0] + dx * i / num_dashes, start_pos[1] + dy * i / num_dashes)end = (start_pos[0] + dx * (i + 1) / num_dashes, start_pos[1] + dy * (i + 1) / num_dashes)pygame.draw.line(screen, color, start, end, 2)# 显示提示信息
def show_message(screen, message, font, color, position):text = font.render(message, True, color)screen.blit(text, position)# 主函数
def main():pygame.init()cols = 35rows = 35cell_size = 20width = cols * cell_sizeheight = rows * cell_sizescreen = pygame.display.set_mode((width, height))pygame.display.set_caption("Random Maze")# 创建迷宫网格grid = [[Cell(j, i) for j in range(cols)] for i in range(rows)]# 生成迷宫generate_maze(grid, cols, rows)# 定义起点和终点start = (0, 0)end = (cols - 1, rows - 1)# 随机添加障碍物obstacle_cells = add_obstacles(grid, cols, rows)# 确保有路径ensure_path_exists(grid, start, end, obstacle_cells)# 初始化玩家位置player_pos = startfont = pygame.font.Font(None, 36)success_text = font.render("Successfully!!!", True, (0, 255, 0))help_text = font.render("", True, (0, 0, 0))success = Falseauto_move = Falserunning = Truewhile running:for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN and not success:if event.key == pygame.K_UP:if can_move(grid, player_pos, 'up'):player_pos = (player_pos[0], player_pos[1] - 1)elif event.key == pygame.K_DOWN:if can_move(grid, player_pos, 'down'):player_pos = (player_pos[0], player_pos[1] + 1)elif event.key == pygame.K_LEFT:if can_move(grid, player_pos, 'left'):player_pos = (player_pos[0] - 1, player_pos[1])elif event.key == pygame.K_RIGHT:if can_move(grid, player_pos, 'right'):player_pos = (player_pos[0] + 1, player_pos[1])elif event.key == pygame.K_SPACE:auto_move = Truepath = find_path(grid, player_pos, end)path_index = 0screen.fill((255, 255, 255))draw_maze(screen, grid, cell_size, cols, rows)draw_start_end(screen, cell_size, start, end)# 绘制路径if 'path' in locals() and path:for i in range(len(path) - 1):start_point = (path[i][0] * cell_size + cell_size // 2, path[i][1] * cell_size + cell_size // 2)end_point = (path[i + 1][0] * cell_size + cell_size // 2, path[i + 1][1] * cell_size + cell_size // 2)draw_dashed_line(screen, (255, 0, 0), start_point, end_point)draw_player(screen, cell_size, player_pos)# 显示提示信息show_message(screen, "", font, (0, 0, 0), (10, 10))if auto_move and 'path' in locals() and path_index < len(path):player_pos = path[path_index]path_index += 1if player_pos == end:auto_move = Falseif player_pos == end:success = Truescreen.blit(success_text,(width // 2 - success_text.get_width() // 2, height // 2 - success_text.get_height() // 2))pygame.display.flip()pygame.time.delay(100)pygame.quit()if __name__ == "__main__":main()

http://www.ppmy.cn/devtools/164654.html

相关文章

PyCharm接入本地部署DeepSeek 实现AI编程!【支持windows与linux】

今天尝试在pycharm上接入了本地部署的deepseek&#xff0c;实现了AI编程&#xff0c;体验还是很棒的。下面详细叙述整个安装过程。 本次搭建的框架组合是 DeepSeek-r1:1.5b/7b Pycharm专业版或者社区版 Proxy AI&#xff08;CodeGPT&#xff09; 首先了解不同版本的deepsee…

【计算机网络入门】初学计算机网络(九)

目录 1.令牌传递协议 2. 局域网&IEEE802 2.1 局域网基本概念和体系结构 3. 以太网&IEEE802.3 3.1 MAC层标准 3.1.1 以太网V2标准 ​编辑 3.2 单播广播 3.3 冲突域广播域 4. 虚拟局域网VLAN 1.令牌传递协议 先回顾一下令牌环网技术&#xff0c;多个主机形成…

MyBatis的关联映射

前言 在实际开发中&#xff0c;对数据库的操作通常会涉及多张表&#xff0c;MyBatis提供了关联映射&#xff0c;这些关联映射可以很好地处理表与表&#xff0c;对象与对象之间的的关联关系。 一对一查询 步骤&#xff1a; 先确定表的一对一关系确定好实体类&#xff0c;添加关…

vue3+nuxt中监听sessionStorage.setItem,数据发生变化动态获取响应

在写项目时&#xff0c;遇见一个未读消息的功能&#xff0c;当消息已读时&#xff0c;减少一条未读消息提示&#xff0c;需要实现当sessionStorage.setItem存储的数据发生改变时&#xff0c;响应式的获取并显示&#xff0c;但是由于sessionStorage 的 setItem 操作本身并不会触…

深度学习-137-LangGraph之应用实例(六)构建RAG问答系统带条件边分支

文章目录 1 大语言模型2 带分支的RAG系统2.1 处理文本构建Document2.2 向量存储2.3 自定义工具2.4 创建图2.4.1 预构建的MessagesState2.4.2 编排图2.4.3 可视化图2.5 测试调用3 参考附录使用langgraph框架构建一个带有条件分支的智能问答系统。创建一个能够从网页文档中提取信…

mac 安装node提示 nvm install v14.21.3 failed可能存在问题

如果你在 macOS 上使用 nvm&#xff08;Node Version Manager&#xff09;安装 Node.js 版本 v14.21.3 时遇到安装失败的问题&#xff0c;可以按照以下步骤进行排查和解决&#xff1a; 1. 确认 nvm 安装是否正确 首先&#xff0c;确认你的 nvm 是否正确安装&#xff0c;并且能…

【FL0093】基于SSM和微信小程序的微信点餐系统小程序

&#x1f9d1;‍&#x1f4bb;博主介绍&#x1f9d1;‍&#x1f4bb; 全网粉丝10W,CSDN全栈领域优质创作者&#xff0c;博客之星、掘金/知乎/b站/华为云/阿里云等平台优质作者、专注于Java、小程序/APP、python、大数据等技术领域和毕业项目实战&#xff0c;以及程序定制化开发…

Ubuntu 下 nginx-1.24.0 源码分析 - ngx_list_init

ngx_list_init 定义在 src\core\ngx_list.h static ngx_inline ngx_int_t ngx_list_init(ngx_list_t *list, ngx_pool_t *pool, ngx_uint_t n, size_t size) {list->part.elts ngx_palloc(pool, n * size);if (list->part.elts NULL) {return NGX_ERROR;}list->par…