Advertisement
Guest User

Untitled

a guest
Jul 19th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.92 KB | None | 0 0
  1. class Maze:
  2. wallRGB, wayRGB = (0, 0, 0), (255, 255, 255)
  3. offset = [(0,2),(0,-2),(-2,0),(2,0)]
  4. def __init__(self, width, height):
  5.  
  6. if width % 2 == 0: width += 1
  7. if height % 2 == 0: height += 1
  8.  
  9. self.width = width
  10. self.height = height
  11.  
  12. # generate an empty maze
  13. self.frontier = []
  14. self.visited = {(1,1)}
  15. self.maze = []
  16.  
  17. for y in range(self.height):
  18. row = []
  19. for x in range(self.width):
  20. if y % 2 + x % 2 < 2: row.append(Maze.wallRGB)
  21. else: row.append(Maze.wayRGB)
  22. self.maze.append(row)
  23.  
  24. #pprint.pprint(self.maze)
  25.  
  26. # starting position
  27. self._addWalls(1,1)
  28.  
  29. def _clamp(n, minN, maxN): return min(max(minN, n), maxN)
  30.  
  31. def _addWalls(self, y, x):
  32. for o in Maze.offset:
  33. cell = (y + o[0], x + o[1])
  34. if self._range(cell[0], cell[1]) and cell not in self.visited and cell not in self.frontier and self.maze[cell[0]][cell[1]] == Maze.wayRGB:
  35. self.frontier.append(cell)
  36.  
  37. def findVisitedNear(self, y, x):
  38. return [(o[0] + y, o[1] + x) for o in Maze.offset if (o[0] + y, o[1] + x) in self.visited]
  39.  
  40. def _range(self, y, x): return 0 <= x < self.width and 0 <= y < self.height
  41.  
  42. def work(self):
  43. while len(self.frontier) > 0:
  44. rand = random.randint(0, len(self.frontier) - 1)
  45. cell = self.frontier.pop(rand)
  46.  
  47. near = self.findVisitedNear(cell[0], cell[1])
  48. inmaze = near[random.randint(0, len(near) - 1)]
  49.  
  50. dy, dx = self._clamp(cell[0] - inmaze[0], -1, 1) , self._clamp(cell[1] - inmaze[1], -1, 1)
  51.  
  52. if dy != 0: self.maze[inmaze[0] + dy][inmaze[1]] = Maze.wayRGB
  53. if dx != 0: self.maze[inmaze[0]][inmaze[1] + dx] = Maze.wayRGB
  54.  
  55. self.visited.add(cell)
  56.  
  57. self._addWalls(cell[0], cell[1])
  58.  
  59. def getMaze(self): return self.maze
  60. def getVisited(self): return self.visited
  61. def getFrontier(self): return self.frontier
  62.  
  63. def workOneStep(self):
  64. if self.frontier > 0:
  65. rand = random.randint(0, len(self.frontier) - 1)
  66. cell = self.frontier.pop(rand)
  67.  
  68. near = self.findVisitedNear(cell[0], cell[1])
  69. inmaze = near[random.randint(0, len(near) - 1)]
  70.  
  71. dy, dx = self._clamp(cell[0] - inmaze[0], -1, 1) , self._clamp(cell[1] - inmaze[1], -1, 1)
  72.  
  73. if dy != 0: self.maze[inmaze[0] + dy][inmaze[1]] = Maze.wayRGB
  74. if dx != 0: self.maze[inmaze[0]][inmaze[1] + dx] = Maze.wayRGB
  75.  
  76. self.visited.add(cell)
  77.  
  78. self._addWalls(cell[0], cell[1])
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement