# -*- 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,
python走迷宫算法以及可视化
最新推荐文章于 2022-06-27 13:40:49 发布
该博客介绍了如何使用Python实现迷宫算法,并通过可视化展示迷宫的生成和解决过程。用户可以通过左侧按钮控制迷宫的开始、结束点,以及地图的布局和尺寸变化。
摘要由CSDN通过智能技术生成