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

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.rhkb.cn/news/26302.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2025-03-01 学习记录--C/C++-PTA 7-35 有理数均值

合抱之木&#xff0c;生于毫末&#xff1b;九层之台&#xff0c;起于累土&#xff1b;千里之行&#xff0c;始于足下。&#x1f4aa;&#x1f3fb; 一、题目描述 ⭐️ 二、代码&#xff08;C语言&#xff09;⭐️ #include <stdio.h>// 【关键】计算最大公约数&#xff…

入门基础项目(SpringBoot+Vue)

文章目录 1. css布局相关2. JS3. Vue 脚手架搭建4. ElementUI4.1 引入ElementUI4.2 首页4.2.1 整体框架4.2.2 Aside-logo4.2.3 Aside-菜单4.2.4 Header-左侧4.2.5 Header-右侧4.2.6 iconfont 自定义图标4.2.7 完整代码 4.3 封装前后端交互工具 axios4.3.1 安装 axios4.3.2 /src…

CAM350_安装

版本&#xff1a;V14.5 一、安装 打开.exe文件 选择不重启&#xff0c;然后再打开这个.exe 再来一次类似的操作 二、配置 复制patch文件夹中的这三个 &#xff0c;粘贴到掉安装目录中 设置ACT_INC_LICENSE_FILE用户环境变量来设置license管理 打开电脑的环境变量 破解完毕&am…

STM32定时器超声波测距实验手册

1. 实验目标 使用STM32 HAL库和定时器实现超声波测距功能。 当超声波模块前方障碍物距离 < 10cm 时&#xff0c;点亮板载LED。 2. 硬件准备 硬件模块说明STM32开发板STM32F103C8T6HC-SR04模块超声波测距模块杜邦线若干连接模块与开发板 3. 硬件连接 HC-SR04引脚STM32引脚…

Open3D解决SceneWidget加入布局中消失的问题

Open3D解决SceneWidget加入布局中消失的问题 Open3D解决SceneWidget加入布局中消失的问题1. 问题2. 问题代码3. 解决 Open3D解决SceneWidget加入布局中消失的问题 1. 问题 把SceneWidget加到布局管理其中图形可以展示出来&#xff0c;但是鼠标点击就消失了。 stackoverflow上已…

9 - QSPI Flash读写测试实验

文章目录 1 实验任务2 系统框图3 软件设计 1 实验任务 本实验任务是使用PS侧的QSPI Flash控制器&#xff0c;先后对QSPI Flash 进行写、 读操作。通过对比读出的数据是否等于写入的数据&#xff0c; 从而验证读写操作是否正确。 2 系统框图 3 软件设计 注意事项&#xff1a;…

简述一下anythingllm与vllm

政安晨的个人主页&#xff1a;政安晨 欢迎 &#x1f44d;点赞✍评论⭐收藏 希望政安晨的博客能够对您有所裨益&#xff0c;如有不足之处&#xff0c;欢迎在评论区提出指正&#xff01; 关于 AnythingLLM 和 VLLM 的技术信息 AnythingLLM 特点与优势 对于主要需求在于文档问答…

JavaScript 数据类型和数据结构:从基础到实践

JavaScript 作为一门动态类型语言&#xff0c;以其灵活性和强大的功能在前端开发中占据了重要地位。理解 JavaScript 的数据类型和数据结构是掌握这门语言的关键。本文将带你深入探讨 JavaScript 中的数据类型、数据结构以及相关的类型检查和转换。 一、原始数据类型&#xff1…

深入解析XXL-JOB任务调度执行原理

引言 ​ 在分布式系统中&#xff0c;定时任务调度是业务场景中不可或缺的一环。面对海量任务、复杂依赖和高可用性要求&#xff0c;传统单机调度方案逐渐显得力不从心。XXL-JOB作为一款开源的分布式任务调度平台&#xff0c;凭借其轻量级、高扩展性和易用性成为众多企业的选择…

为AI聊天工具添加一个知识系统 之127 详细设计之68 编程 核心技术:Cognitive Protocol Language 之1

本文要点 要点 今天讨论的题目&#xff1a;本项目&#xff08;为使用AI聊天工具的两天者加挂一个知识系统&#xff09; 详细程序设计 之“编程的核心技术” 。 source的三个子类&#xff08;Instrument, Agent, Effector&#xff09; 分别表示--实际上actually &#xff0c;…

word转换为pdf后图片失真解决办法、高质量PDF转换方法

1、安装Adobe Acrobat Pro DC 自行安装 2、配置Acrobat PDFMaker &#xff08;1&#xff09;点击word选项卡上的Acrobat插件&#xff0c;&#xff08;2&#xff09;点击“首选项”按钮&#xff0c;&#xff08;3&#xff09;点击“高级配置”按钮&#xff08;4&#xff09;点…

Kafka生产者相关

windows中kafka集群部署示例-CSDN博客 先启动集群或者单机也OK 引入依赖 <dependency><groupId>org.apache.kafka</groupId><artifactId>kafka-clients</artifactId><version>3.9.0</version></dependency>关于主题创建 理论…

《Effective Objective-C》阅读笔记(下)

目录 内存管理 理解引用计数 引用计数工作原理 自动释放池 保留环 以ARC简化引用计数 使用ARC时必须遵循的方法命名规则 变量的内存管理语义 ARC如何清理实例变量 在dealloc方法中只释放引用并解除监听 编写“异常安全代码”时留意内存管理问题 以弱引用避免保留环 …

一、对iic类模块分析与使用

bmp280驱动代码 说明&#xff1a; 1、该模块用于获取气压&#xff0c;温度&#xff0c;海拔等数据。 vcc&#xff0c;gnd接电源 sda &#xff0c;scl 接iic通信引脚 2、该模块使用iic通信&#xff0c;通过iic发送请求相关类的寄存器值&#xff0c;芯片获取对应寄存器返回的数据…

辛格迪客户案例 | 祐儿医药科技GMP培训管理(TMS)项目

01 项目背景&#xff1a;顺应行业趋势&#xff0c;弥补管理短板 随着医药科技行业的快速发展&#xff0c;相关法规和标准不断更新&#xff0c;对企业的质量管理和人员培训提出了更高要求。祐儿医药科技有限公司&#xff08;以下简称“祐儿医药”&#xff09;作为一家专注于创新…

汽车低频发射天线介绍

汽车低频PKE天线是基于RFID技术的深度研究及产品开发应用的一种天线&#xff0c;在汽车的智能系统中发挥着重要作用&#xff0c;以下是关于它的详细介绍&#xff1a; 移动管家PKE低频天线结构与原理 结构&#xff1a;产品一般由一个高Q值磁棒天线和一个高压电容组成&#xff…

Java 大视界 -- Java 大数据分布式文件系统的性能调优实战(101)

&#x1f496;亲爱的朋友们&#xff0c;热烈欢迎来到 青云交的博客&#xff01;能与诸位在此相逢&#xff0c;我倍感荣幸。在这飞速更迭的时代&#xff0c;我们都渴望一方心灵净土&#xff0c;而 我的博客 正是这样温暖的所在。这里为你呈上趣味与实用兼具的知识&#xff0c;也…

全国普通高等学校名单

全国普通高等学校名单 全国普通高等院校&#xff0c;简称“高校”&#xff0c;是指那些提供高等教育的学校&#xff0c;涵盖了大学、独立学院、高等专科学校以及高等职业学校等多种类型。这些机构通过国家普通高等教育招生考试&#xff0c;主要招收高中毕业生&#xff0c;并为…

Vue.js 学习笔记

文章目录 前言一、Vue.js 基础概念1.1 Vue.js 简介1.2 Vue.js 的特点1.3 Vue.js 基础示例 二、Vue.js 常用指令2.1 双向数据绑定&#xff08;v-model&#xff09;2.2 条件渲染&#xff08;v-if 和 v-show&#xff09;2.3 列表渲染&#xff08;v-for&#xff09;2.4 事件处理&am…

【Python】基础语法三

> 作者&#xff1a;დ旧言~ > 座右铭&#xff1a;松树千年终是朽&#xff0c;槿花一日自为荣。 > 目标&#xff1a;了解Python的函数、列表和数组。 > 毒鸡汤&#xff1a;有些事情&#xff0c;总是不明白&#xff0c;所以我不会坚持。早安! > 专栏选自&#xff…