我正在開發一個建立完美迷宮的項目。 我有一個迷宮類和一個類代表迷宮中的每個方格。在我的Cell類中,我有四個布爾變量(北,南,東,西)來表示單元格的北部還是南部有一堵牆。還有一個名爲visit的布爾變量來檢查單元是否被訪問過。這裏是我的代碼,用於Cell類的init()。檢查完美迷宮的輸入驗證
def __init__(self):
self.north = True
self.south = True
self.east = True
self.west = True
self.visit = False
而對於迷宮類,我有self.maze(一堆細胞)和self.size = N(構建一個N * N的迷宮)。 下面是類迷宮的INIT():
def __init__(self, N):
self.size = N
self.maze = [[i for i in range(N + 2)] for i in range(N + 2)]
for r in range(self.size + 2):
for c in range(self.size + 2):
self.maze[r][c] = Cell()
雖然我更新迷宮的索引,我寫了兩個函數來檢查下一頁末和newY是否在範圍爲1 < = X < = self.size和1 < = y < = self.size,以及是否已訪問該單元格。 下面是代碼:
def in_range(self, x, y):
if 1 <= x <= self.size and 1 <= y <= self.size:
return True
else:
return False
def is_valid(self, x, y):
if not self.maze[x][y].getVisit() and self.in_range(x,y):
return True
else:
return False
這一切後,我寫的主要結構:
def walk(self, s, x, y):
neighbor = [(x + 1, y), (x - 1, y), (x, y + 1), (x, y - 1)]
if s.size() == self.size**2: return
else:
while True:
new = choice(neighbor)#choice() is import from random
#print(self.is_valid(new[0], new[1]))
if self.is_valid(new[0], new[1]):break
else:
if len(neighbor) != 0:
neighbor.remove(new)
new = choice(neighbor)
else:
temp = s.pop(s)
self.walk(s, temp[0], temp[1])
break
print(new)
但是,運行我的代碼劇照給我的指標是不是1和self.size之間。我無法弄清楚爲什麼,我認爲我的檢查算法工作正常。 這是我得到的:
>>> ================================ RESTART
================================
>>>
>>> a = Maze(5)
>>> a.search()
1 2
(1, 3)
(2, 3)
(2, 4)
(1, 4)
(2, 4)
(2, 5)
(3, 5)
(4, 5)
(4, 4)
(4, 3)
(3, 3)
(3, 2)
(2, 2)
(2, 1)
(1, 1)
(0, 1)
(-1, 1)
(0, 1)
(1, 1)
(0, 1)
(-1, 1)
(-1, 2)
(-1, 1)
(0, 1)
有人可以幫我嗎? PLZ,真的很感激!
它是[build-a-perfect-maze](http://stackoverflow.com/questions/29450400/build-a-perfect-maze-recursively-in-python)又是一週嗎? – 2015-04-05 07:42:05
爲什麼到處使用'range(N + 2)'?這將創建一個(N + 1)x(N + 1)迷宮。只需創建Cell的[numpy.array](http://docs.scipy.org/doc/numpy/reference/generated/numpy.array.html)。 – smci 2015-04-05 08:28:44
很高興提供幫助。你能否將你的班級代碼發佈到迷宮和單元? – 2015-04-05 09:11:16