Python实现动态迷宫生成:自动生成迷宫的动画


在这里插入图片描述

引言

迷宫生成算法在游戏开发和图形学中有着广泛的应用。它不仅可以用于创建迷宫游戏,还可以用于生成有趣的图案。在这篇博客中,我们将使用Python创建一个动态迷宫生成的动画效果。通过利用Pygame库和深度优先搜索算法,我们可以实现一个自动生成迷宫的动画。

准备工作

前置条件

在开始之前,你需要确保你的系统已经安装了Pygame库。如果你还没有安装它,可以使用以下命令进行安装:

pip install pygame

Pygame是一个跨平台的Python模块,用于编写视频游戏。它包括计算机图形和声音库,使得游戏开发更加简单。

代码实现与解析

导入必要的库

我们首先需要导入Pygame库和其他必要的模块:

import pygame
import random

初始化Pygame

我们需要初始化Pygame并设置屏幕的基本参数:

pygame.init()
screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption("动态迷宫生成")
clock = pygame.time.Clock()

定义迷宫生成类

我们创建一个Maze类来定义迷宫的属性和生成行为:

class Maze:
    def __init__(self, width, height, cell_size):
        self.width = width
        self.height = height
        self.cell_size = cell_size
        self.cols = width // cell_size
        self.rows = height // cell_size
        self.grid = [[0 for _ in range(self.cols)] for _ in range(self.rows)]
        self.stack = []
        self.current_cell = (0, 0)
        self.visited_cells = 1
        self.total_cells = self.cols * self.rows

    def draw_cell(self, screen, x, y, color):
        pygame.draw.rect(screen, color, (x * self.cell_size, y * self.cell_size, self.cell_size, self.cell_size))

    def draw_grid(self, screen):
        for y in range(self.rows):
            for x in range(self.cols):
                color = (255, 255, 255) if self.grid[y][x] else (0, 0, 0)
                self.draw_cell(screen, x, y, color)

    def generate_maze(self):
        if self.visited_cells < self.total_cells:
            x, y = self.current_cell
            self.grid[y][x] = 1
            neighbors = self.get_unvisited_neighbors(x, y)
            if neighbors:
                next_cell = random.choice(neighbors)
                self.stack.append(self.current_cell)
                self.remove_wall(self.current_cell, next_cell)
                self.current_cell = next_cell
                self.visited_cells += 1
            elif self.stack:
                self.current_cell = self.stack.pop()

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

    def remove_wall(self, current, next):
        x1, y1 = current
        x2, y2 = next
        self.grid[(y1 + y2) // 2][(x1 + x2) // 2] = 1

主循环

我们在主循环中更新迷宫的生成状态并绘制:

maze = Maze(800, 800, 20)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((0, 0, 0))
    
    maze.generate_maze()
    maze.draw_grid(screen)

    pygame.display.flip()
    clock.tick(30)

pygame.quit()

完整代码

import pygame
import random

# 初始化Pygame
pygame.init()
screen = pygame.display.set_mode((800, 800))
pygame.display.set_caption("动态迷宫生成")
clock = pygame.time.Clock()

# 迷宫类定义
class Maze:
    def __init__(self, width, height, cell_size):
        self.width = width
        self.height = height
        self.cell_size = cell_size
        self.cols = width // cell_size
        self.rows = height // cell_size
        self.grid = [[0 for _ in range(self.cols)] for _ in range(self.rows)]
        self.stack = []
        self.current_cell = (0, 0)
        self.visited_cells = 1
        self.total_cells = self.cols * self.rows

    def draw_cell(self, screen, x, y, color):
        pygame.draw.rect(screen, color, (x * self.cell_size, y * self.cell_size, self.cell_size, self.cell_size))

    def draw_grid(self, screen):
        for y in range(self.rows):
            for x in range(self.cols):
                color = (255, 255, 255) if self.grid[y][x] else (0, 0, 0)
                self.draw_cell(screen, x, y, color)

    def generate_maze(self):
        if self.visited_cells < self.total_cells:
            x, y = self.current_cell
            self.grid[y][x] = 1
            neighbors = self.get_unvisited_neighbors(x, y)
            if neighbors:
                next_cell = random.choice(neighbors)
                self.stack.append(self.current_cell)
                self.remove_wall(self.current_cell, next_cell)
                self.current_cell = next_cell
                self.visited_cells += 1
            elif self.stack:
                self.current_cell = self.stack.pop()

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

    def remove_wall(self, current, next):
        x1, y1 = current
        x2, y2 = next
        self.grid[(y1 + y2) // 2][(x1 + x2) // 2] = 1

# 主循环
maze = Maze(800, 800, 20)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((0, 0, 0))
    
    maze.generate_maze()
    maze.draw_grid(screen)

    pygame.display.flip()
    clock.tick(30)

pygame.quit()

相关推荐

  1. 自制迷宫游戏 c++

    2024-07-12 02:46:03       22 阅读
  2. 自动生成请假条 - Python实现

    2024-07-12 02:46:03       63 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 02:46:03       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 02:46:03       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 02:46:03       57 阅读
  4. Python语言-面向对象

    2024-07-12 02:46:03       68 阅读

热门阅读

  1. C++list的模拟实现

    2024-07-12 02:46:03       25 阅读
  2. Zookeeper-数据结构

    2024-07-12 02:46:03       23 阅读
  3. c++ learn five five day

    2024-07-12 02:46:03       22 阅读
  4. 自定义激活函数:Mojo模型的动态选择之道

    2024-07-12 02:46:03       21 阅读
  5. Docker-12 Docker常用命令

    2024-07-12 02:46:03       17 阅读
  6. HJ2 计算某字符出现次数 、 HJ3 明明的随机数

    2024-07-12 02:46:03       21 阅读
  7. 什么是Stream流

    2024-07-12 02:46:03       20 阅读
  8. playwright下载文件如何不被删除

    2024-07-12 02:46:03       17 阅读
  9. c#中的超时终止

    2024-07-12 02:46:03       18 阅读
  10. 归并排序算法Python实现

    2024-07-12 02:46:03       22 阅读
  11. 07-7.4.2 B+树

    2024-07-12 02:46:03       19 阅读
  12. 生信技能52 - VCF文件hg38与hg19坐标相互转换

    2024-07-12 02:46:03       20 阅读
  13. 技术总结(1)——方向与成长思考

    2024-07-12 02:46:03       23 阅读
  14. 《穿透财报:读懂财报中的逻辑与陷阱》

    2024-07-12 02:46:03       21 阅读
  15. Spring——自动装配Bean

    2024-07-12 02:46:03       21 阅读
  16. 前端高頻面試題(一)

    2024-07-12 02:46:03       22 阅读