python走迷宫算法以及可视化

该博客介绍了如何使用Python实现迷宫算法,并通过可视化展示迷宫的生成和解决过程。用户可以通过左侧按钮控制迷宫的开始、结束点,以及地图的布局和尺寸变化。
摘要由CSDN通过智能技术生成
# -*- coding: utf-8 -*-
# 单文件版本
from __future__ import unicode_literals
import random

try:
    from tkinter import *
except ImportError:
    from Tkinter import *
import matplotlib.image as mpimg  # 用于显示图片
import numpy


class Block(object):
    def __init__(self, mmap, x, y, direction=None):
        super(Block, self).__init__()
        # 初始定义四个方向都没有堵塞
        self.walls = [True, True, True, True]  # top,right,bottom,left
        self.mmap = mmap
        if mmap:
            mmap.mmap[x][y] = self
        self.x, self.y = x, y
        # 根据算法设置堵塞的墙
        if direction is not None:
            direction = (direction + 2) % 4
            self.walls[direction] = False

    def __unicode__(self):
        return "%s" % [1 if e else 0 for e in self.walls]

    def __str__(self):
        return unicode(self).encode('utf-8')

    # 根据已有点的位置坐标,获取周围四个方向的坐标
    def get_next_block_pos(self, direction):
        x = self.x
        y = self.y
        if direction == 0:  # Top
            y -= 1
        elif direction == 1:  # Right
            x += 1
        if direction == 2:  # Bottom
            y += 1
        if direction == 3:  # Left
            x -= 1
        return x, y

    def get_next_block(self):
        directions = list(range(4))  # 四个方向
        random.shuffle(directions)  # 随机找一个方向
        for direction in directions:  # 每个方向遍历查找
            x, y = self.get_next_block_pos(direction)  # 下一个方向的坐标
            if x >= self.mmap.max_x or x < 0 or y >= self.mmap.max_y or y < 0:
                continue  # 可以往下走
            if self.mmap.mmap[x][y]:  # if walked
                continue  # 走了
            self.walls[direction] = False  # 此路不通
            return Block(self.mmap, x,
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值