a9acab05 |
from __future__ import print_function
import numpy as np
class Traveller(object):
@property
def x(self): return self.pos[0]
@x.setter
def x(self, val): self.pos = val, self.pos[1]
@property
def y(self): return self.pos[1]
@y.setter
def y(self, val): self.pos = self.pos[0], val
def __init__(self, starting_cell):
self.pos = (0,0)
self.connections = []
self.visited = set()
self.thresh = 0.5# np.random.normal(0.5, 0.15)
print(self.thresh)
def random_walk(self, array):
if self.x >= array.shape[0]:
return True
else:
row = array[self.x]
for self.y in range(array.shape[1]-1):
if row[self.y] != row[self.y+1] and np.random.random() < self.thresh:
row[self.y+1] = row[self.y]
self.connections.append(((self.x, self.y), (self.x, self.y+1)))
#self.visited.add((self.x, self.y))
new = [0]*array.shape[0]
if self.x < array.shape[0]-2:
new, idxs = prop_down(array[self.x])
self.connections.extend(((self.x, y),(self.x+1,y)) for y in idxs)
first_virt = False
if self.x == array.shape[0]-1:
for idx in range(array.shape[1]-1):
if array[self.x-1][idx] != array[self.x-1][idx+1]:
self.connections.append(((self.x-1, idx), (self.x, idx)))
self.connections.append(((self.x-1, idx+1), (self.x, idx+1)))
self.connections.append(((self.x, idx), (self.x, idx+1)))
if not first_virt:
self.connections.append(((self.x, idx-1), (self.x, idx)))
first_virt = True
else:
self.connections.append(((self.x, idx-1), (self.x, idx)))
lrow = array[self.x-1]
if lrow[-2] == lrow[-1]:
self.connections.append(((self.x, array.shape[1]-2), (self.x, array.shape[1]-1)))
self.x += 1
if self.x < array.shape[0]-1:
array[self.x] = new
import random
def prop_down(row, early=False):
def collect(r):
out = [[(0,r[0])]]
for idx,x in enumerate(r[1:],1):
if x != out[-1][-1][1]:
out.append([])
out[-1].append((idx,x))
return [[x[0] for x in y] for y in out]
idxs = collect(row)
prop = map(random.choice, idxs)
new = [0]*len(row)
for x in prop: new[x] = row[x]
if not early:
unused = set(range(1,len(row)+1)) - set(new)
for idx,x in enumerate(new):
if x == 0:
new[idx] = unused.pop()
return new, prop
x,y = 39,19
maze = np.zeros((x,y), int)
maze[0] = range(1,y+1)
maze.shape = x,y
t = Traveller((x/2, y/2))
if __name__ == '__main__':
import display
import time
while True:
print('c')
self = display.MazeDigger(t, (x,y))
t.random_walk(maze)
self.make_map()
self.show_map()
time.sleep(0.4)
print()
|