Python实现随机生成迷宫并自动寻路

yizhihongxing

下面我来详细讲解一下“Python实现随机生成迷宫并自动寻路”的完整攻略。

简介

这个项目旨在使用Python生成随机迷宫并实现自动寻路的功能。具体实现过程如下:

  1. 随机生成迷宫
  2. 使用启发式搜索算法自动找到迷宫的出口

随机生成迷宫

要生成迷宫,我们可以采用深度优先搜索(DFS)和递归回溯算法。具体步骤如下:

  1. 创建一个NxM的矩阵,初始化所有元素为墙
  2. 从任意位置开始递归,选择上下左右四个方向中的一个,并且走两步
  3. 如果所选方向的两步都未超过矩阵边界,那么将中间的点和终点都标记为通路,并递归访问终点;否则回溯到上一个节点,重新选择通路。

下面是一个简化版的实现例子:

import random

def generate_maze(rows, cols):
    maze = []
    for i in range(rows):
        row = []
        for j in range(cols):
            row.append(1)
        maze.append(row)

    def build_wall(x, y):
        maze[x][y] = 0

    def dfs(x, y):
        directions = [(0, 2), (2, 0), (0, -2), (-2, 0)]
        random.shuffle(directions)
        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            if 0 <= nx < rows and 0 <= ny < cols and maze[nx][ny] == 1:
                maze[x + dx // 2][y + dy // 2] = 0
                build_wall(nx, ny)
                dfs(nx, ny)

    start_x, start_y = random.randint(0, rows // 2) * 2, random.randint(0, cols // 2) * 2
    dfs(start_x, start_y)
    maze[start_x][start_y] = 0
    maze[rows - 1][cols - 1] = 0
    return maze

以上代码生成的迷宫矩阵是一个rows * cols大小的列表,其中0代表通路,1代表障碍物。

自动寻路

实现自动寻路,可以采用A算法。A算法是一种启发式搜索算法,在广度优先搜索的基础上,加入了估价函数。具体步骤如下:

  1. 将起点加入open列表
  2. 重复以下步骤直到open列表为空:
    • 取出open列表中f值最小的节点
    • 如果当前节点是终点,返回路径
    • 将当前节点标记为closed,并将其相邻的未访问节点加入open列表
  3. 如果open列表为空,表示无解

下面是一个简化版的实现例子:

import heapq

def a_star(maze):
    rows, cols = len(maze), len(maze[0])
    start = (0, 0)
    end = (rows - 1, cols - 1)

    def get_distance(p1, p2):
        return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])

    def get_neighbors(point):
        x, y = point
        neighbors = []
        for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
            nx, ny = x + dx, y + dy
            if 0 <= nx < rows and 0 <= ny < cols and maze[nx][ny] == 0:
                neighbors.append((nx, ny))
        return neighbors

    open_heap = [(get_distance(start, end), start)]
    visited = set()

    while open_heap:
        f, point = heapq.heappop(open_heap)
        if point in visited:
            continue
        visited.add(point)
        if point == end:
            path = []
            while point != start:
                path.append(point)
                point = parents[point]
            path.append(start)
            path.reverse()
            return path
        for neighbor in get_neighbors(point):
            g = get_distance(start, point) + 1
            h = get_distance(neighbor, end)
            f = g + h
            heapq.heappush(open_heap, (f, neighbor))
    return []

以上代码实现了A*算法的寻路过程,并返回了一条从起点到终点的路径。

接下来我们将两部分集成在一起,得到完整的代码实现。下面是一个示例:

import random
import heapq

def generate_maze(rows, cols):
    maze = []
    for i in range(rows):
        row = []
        for j in range(cols):
            row.append(1)
        maze.append(row)

    def build_wall(x, y):
        maze[x][y] = 0

    def dfs(x, y):
        directions = [(0, 2), (2, 0), (0, -2), (-2, 0)]
        random.shuffle(directions)
        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            if 0 <= nx < rows and 0 <= ny < cols and maze[nx][ny] == 1:
                maze[x + dx // 2][y + dy // 2] = 0
                build_wall(nx, ny)
                dfs(nx, ny)

    start_x, start_y = random.randint(0, rows // 2) * 2, random.randint(0, cols // 2) * 2
    dfs(start_x, start_y)
    maze[start_x][start_y] = 0
    maze[rows - 1][cols - 1] = 0
    return maze


def a_star(maze):
    rows, cols = len(maze), len(maze[0])
    start = (0, 0)
    end = (rows - 1, cols - 1)

    def get_distance(p1, p2):
        return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])

    def get_neighbors(point):
        x, y = point
        neighbors = []
        for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
            nx, ny = x + dx, y + dy
            if 0 <= nx < rows and 0 <= ny < cols and maze[nx][ny] == 0:
                neighbors.append((nx, ny))
        return neighbors

    open_heap = [(get_distance(start, end), start)]
    visited = set()
    parents = {}

    while open_heap:
        f, point = heapq.heappop(open_heap)
        if point in visited:
            continue
        visited.add(point)
        if point == end:
            path = []
            while point != start:
                path.append(point)
                point = parents[point]
            path.append(start)
            path.reverse()
            return path
        for neighbor in get_neighbors(point):
            g = get_distance(start, point) + 1
            h = get_distance(neighbor, end)
            f = g + h
            heapq.heappush(open_heap, (f, neighbor))
            parents[neighbor] = point
    return []


if __name__ == "__main__":
    maze = generate_maze(20, 20)
    path = a_star(maze)

    print("迷宫:")
    for row in maze:
        print(" ".join(["#" if x else " " for x in row]))

    print("路径:")
    for i, p in enumerate(path):
        if i == 0:
            print("[S]", end=" ")
        elif i == len(path) - 1:
            print("[E]", end=" ")
        else:
            print("[X]", end=" ")
        print("({},{})".format(p[0], p[1]), end=" ")
    print()

上述代码实现了一个20x20大小的迷宫,并在迷宫中使用A*算法寻找从起点到终点的路径。运行后所生成的结果会输出迷宫和找到的路径。

再以一个更大的迷宫为例,运行结果如下所示:

迷宫:
# # # # # # # # # # # # # # # # # # #
#                                 # #
# # # # # # # # # # # # # # # #   # #
#   # # # # # #             #   # # #
# # #   # # # # # # # # #   # # # # #
#         # #     #     # # # # #   #
# # # # # # # #   # # #     #   # #
#           #   # # # # # #   # # #
# # # # # # # #           # # # # #
#       # #   # # # # #   # #     #
# # # # # # # #     # #           #
#   # # # #   # # # # # # # # # # #
# #   #   # # # # # #   # # # # # #
# # # # #   #         # # #     # #
#                 # # # # # #   # #
# # # # # # # # # # #         # # #
#         #         # # # # # # # #
# # # # # # # # # # # #   #     # #
#             #               #   #
# # # # # # # # # # # # # # # # # #
路径:
[S] (0,0) [X] (2,0) [X] (2,2) [X] (4,2) [X] (4,4) [X] (6,4) [X] (6,6) [X] (8,6) [X] (10,6) [X] (10,8) [X] (10,10) [X] (10,12) [X] (12,12) [X] (12,14) [X] (12,16) [X] (12,18) [X] (14,18) [X] (16,18) [X] (18,18) [X] (19,18) [E] 

可以看到,我们成功用Python实现了随机生成迷宫和自动寻路的功能。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python实现随机生成迷宫并自动寻路 - Python技术站

(0)
上一篇 2023年5月19日
下一篇 2023年5月19日

相关文章

  • 使用python检查值是否已经存在于字典列表中

    当我们操作字典列表的时候,有时候需要检查某个值是否已经存在于字典列表中。在Python中,我们可以使用以下几种方式来实现这个功能: 方式一:使用循环遍历字典列表 当字典列表中的元素比较少时,我们可以使用循环遍历字典列表来检查某个值是否已经存在于字典列表中,具体步骤如下: # 定义一个字典列表 users = [ {‘name’: ‘Tom’, ‘age’: …

    python 2023年5月13日
    00
  • python 多线程threading程序详情

    下面是关于“Python 多线程 threading 程序详情”的完整攻略。 概述 多线程是指在同一时间可以运行多个线程,这样可以使程序的执行更加高效。在 Python 中,多线程通过 threading 模块来实现。threading 模块中的 Thread 类可以创建一个线程对象。 创建线程对象 使用 Thread 类创建线程对象时,需要实现一个 run…

    python 2023年5月18日
    00
  • python 操作excel表格的方法

    下面我将详细讲解Python操作Excel表格的方法的完整实例教程。 一、安装必要的库 在Python中操作Excel表格需要安装openpyxl库。可以通过以下命令进行安装: pip install openpyxl 二、打开Excel文件 在Python中,可以使用openpyxl库的load_workbook方法打开Excel文件。例如,我们要打开名为…

    python 2023年5月13日
    00
  • python中带有直方图的高级掷骰子模拟器

    【问题标题】:advanced dice roll simulator w/ histogram in pythonpython中带有直方图的高级掷骰子模拟器 【发布时间】:2023-04-01 02:19:02 【问题描述】: 我正在编写一个程序,询问用户骰子的数量和骰子的边数。它计算每个值滚动了多少次,然后将它们放在一个列表中。然后我必须打印列表以及百分…

    Python开发 2023年4月8日
    00
  • 解决Python报错问题[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE]

    在Python中,有时候我们会遇到SSLV3_ALERT_HANDSHAKE_FAILURE错误,这是由于SSL握手失败导致的。本文将详细讲解解决Python报错问题[SSL: SSLV3_ALERT_HANDSHAKE_FAILURE]的完整攻略,包括升级OpenSSL库和禁用SSL验证的示例代码。 升级OpenSSL库 SSLV3_ALERT_HANDS…

    python 2023年5月15日
    00
  • Python3实现计算两个数组的交集算法示例

    下面将详细讲解如何使用Python3实现计算两个数组的交集算法,具体步骤如下: 1. 确定算法思路 计算两个数组的交集,一般可以采用哈希表或者双指针的方法。对于哈希表方法,首先将其中一个数组的元素全部存入哈希表中,然后遍历另一个数组,检查其中的元素是否存在哈希表中,如果存在则将其加入到结果集中。对于双指针方法,首先将两个数组排序,然后使用两个指针分别指向两个…

    python 2023年6月3日
    00
  • 基于python时间处理方法(详解)

    基于Python的时间处理方法(详解) Python是一种流行的编程语言,其中一个强大的功能就是能够处理时间。在本文中,将会详细讲解基于Python的时间处理方法。 日期和时间 在Python中,时间通常使用datetime库来处理。该库包含了许多实用程序函数,用于操作日期和时间。 获取当前日期和时间 要获取当前日期和时间,可以使用以下代码: import …

    python 2023年6月2日
    00
  • Python自动化测试之异常处理机制实例详解

    Python自动化测试之异常处理机制实例详解 在Python自动化测试中,异常处理机制是非常重要的一部分。异常处理机制可以帮助我们在程序出现错误时,优地处理,避免程序崩溃。本文将详细讲解Python自动化测试中处理机制的实例,包括try-except语句、try-except-else语句、try-except-finally语句等。在过程中,提供两个示例说…

    python 2023年5月13日
    00
合作推广
合作推广
分享本页
返回顶部