我的程序遇到一个小问题,因为我对Python很陌生,正在努力寻找解决方案。我已经google了一下,但似乎没有任何东西可以解决我的尝试。我的代码如下:
from PIL import Image
import numpy as np
from scipy import misc
from pandas import *
def maze_gen():
##Opens the Image
im_file = Image.open('15x15.png')
##Reads the image pixel information
arr = misc.imread('15x15.png')
##Sets the width, height and maze size variables
width = im_file.size[0]
height = im_file.size[1]
size = width * height
##Defines the mapping, start and end points array
map = np.zeros([width, height], dtype=np.int)
start_pos = np.empty(shape=[1,2])
end_pos = np.empty(shape=[1,2])
##Search image replacing white pixels with 1's in the mapping array
for x in range(width):
for y in range(height):
if 255 in arr[x,y]:
map[x,y] = 1
##Find the start and end locations
for x in range(width):
if map[0,x] > 0:
start_pos = 0,x
for x in range(width):
if map[height -1 ,x] > 0:
end_pos = height -1 ,x
return width, height, size, map, start_pos, end_pos
def check_neighbours(col, row):
width, height, size, map, start_pos, end_pos=maze_gen()
neighbours = list()
##Debugging to check cell_current values are correct
print('col =', col)
print('row =', row)
if (col >= 0 and col < height and row >= 0 and row < width):
neighbours.append((col, row))
print('Neighbours', neighbours, '\n')
if (len(neighbours) > 0):
return neighbours
else:
return None
def solver():
width, height, size, map, start_pos, end_pos=maze_gen()
##Sets cell_current to the starting position
cell_current = start_pos
path = list()
path.append((cell_current))
check_neighbours(cell_current[0]-1, cell_current[1]) ##Top neighbour
check_neighbours(cell_current[0], cell_current[1]+1) ##Right neighbour
check_neighbours(cell_current[0]+1, cell_current[1]) ##Bottom neighbour
check_neighbours(cell_current[0], cell_current[1]-1) ##Left neighbour
print('Neighbours in Solver', neighbours, '\n')
def debug():
width, height, size, map, start_pos, end_pos=maze_gen()
##Prints maze information for debugging
print ('Maze width:', width)
print ('Maze height:', height)
print ('Maze size:', size, '\n')
##Print Start and End points
print ('Start Point')
print (start_pos, '\n')
print ('End Point')
print (end_pos, '\n')
##Prints mapping array for debugging
print ('Mapping Array')
print (DataFrame(map), '\n')
if (__name__ == "__main__"):
solver()
我遇到的问题是,每次成功运行if语句时都不会添加邻居列表。而不是获得以下读数:
col = -1 row = 1 Neighbors []
col = 0 row = 2 Neighbors [(0,2)]
col = 1 row = 1 Neighbors [(1,1)]
col = 0 row = 0 Neighbors [(0,0)]
对这个问题的任何帮助都会很棒。请记住我是python的新手,所以任何愚蠢的错误或我可以改变以使代码更好的事情请说!
答案 0 :(得分:0)
您需要在代码中进行两项更改:
将邻居变量设为全局。
用 neighbours.append([col,row])替换 neighbours.append((col,row))。这是因为您只能将变量或列表附加到现有列表。
希望这会有所帮助。