Mat*_*bel 9 python maze list append
我的Python迷宫生成程序似乎有问题.我正在尝试随机创建一个在选定点分支出来的路径,这些点随着它的存在而被存储起来.当迷宫到达死胡同时,它将通过测试最高值而不是弹出并转到下一个点来回溯通过被访问点,直到它到达不是死路的地方.但是,当我尝试将项目附加到列表中时,我用来保存我去过的空间,发生了一些奇怪的事情,我实际上从未见过它.这是代码,最好的方法是运行它直到它一直运行.我还没有真正找到解决死胡同问题的办法,所以如果有人也可以帮助我,那就太好了.
import random
width = 8
def check(x,y):
"""Figures out the directions that Gen can move while"""
if x-1 == -1:
maze[x][y][3] = 0
if x+1 == 8:
maze[x][y][1] = 0
if y+1 == 8:
maze[x][y][2] = 0
if y-1 == -1:
maze[x][y][0] = 0
if x + 1 in range(0,8) and visited[x+1][y] == False:
maze[x][y][1] = 2
if x - 1 in range(0,8) and visited[x-1][y] == False:
maze[x][y][3] = 2
if y + 1 in range(0,8) and visited[x][y+1] == False:
maze[x][y][2] = 2
if y - 1 in range(0,8) and visited[x][y-1] == False:
maze[x][y][0] = 2
def Gen(x,y):
visited[x][y] = True
past.append(current)
dirs = []
check(x,y)
print current
if maze[x][y][0] == 2:
dirs.append(0)
if maze[x][y][1] == 2:
dirs.append(1)
if maze[x][y][2] == 2:
dirs.append(2)
if maze[x][y][3] == 2:
dirs.append(3)
pos = random.choice(dirs)
print dirs
maze[x][y][pos] = 1
if pos == 0:
current[1] -= 1
if pos == 1:
current[0] += 1
if pos == 2:
current[1] += 1
if pos == 3:
current[0] -= 1
if maze[x][y][0] == 4:
maze[x][y][0] = 1
if maze[x][y][1] == 4:
maze[x][y][1] = 1
if maze[x][y][2] == 4:
maze[x][y][2] = 1
if maze[x][y][3] == 4:
maze[x][y][3] = 1
print maze[x][y]
print past, '\n'
#Build the initial values for the maze to be replaced later
maze = []
current = [0,0]
visited = []
past = []
#Generate empty 2d list with a value for each of the xy coordinates
for i in range(0,width):
maze.append([])
for q in range(0, width):
maze[i].append([])
for n in range(0, 4):
maze[i][q].append(4)
#Makes a list of falses for all the non visited places
for x in range(0, width):
visited.append([])
for y in range(0, width):
visited[x].append(False)
#Generates the walls
#for q in range(0, width):
# for i in range(0, width):
# check(q, i)
current = [0,0]
while current != [7,7]:
Gen(current[0], current[1])
print maze
Run Code Online (Sandbox Code Playgroud)
如您所见,它从0,0开始,然后计算出可能的路径.它从那些中随机选择,并将房间那边的值设置为0,0到1,这意味着一个段落.2表示墙,0表示越界.4只是占位符,因为所有值都应该在迷宫完全生成时填充.
如果有人能帮助我,那将是伟大的,非常感激.提前致谢.
dap*_*wit 13
我相信current
列表只是被复制多次past
.所以你有同一个列表的多个副本.
要修复:在行中past.append(current)
(下面两行def Gen(x,y):
),将其更改为past.append(current[:])
.
表示法list[:]
创建列表的副本.从技术上讲,您正在创建整个列表的一部分.
顺便说一下,更好的解决方案是不使用全局current
变量:)