Maze Algorithm


SUBMITTED BY: Guest

DATE: Nov. 11, 2013, 4:18 p.m.

FORMAT: Python

SIZE: 1.6 kB

HITS: 864

  1. import numpy
  2. from numpy.random import random_integers as rand
  3. import matplotlib.pyplot as pyplot
  4. def maze(width=81, height=51, complexity=.75, density=.75):
  5. # Only odd shapes
  6. shape = ((height // 2) * 2 + 1, (width // 2) * 2 + 1)
  7. # Adjust complexity and density relative to maze size
  8. complexity = int(complexity * (5 * (shape[0] + shape[1])))
  9. density = int(density * (shape[0] // 2 * shape[1] // 2))
  10. # Build actual maze
  11. Z = numpy.zeros(shape, dtype=bool)
  12. # Fill borders
  13. Z[0, :] = Z[-1, :] = 1
  14. Z[:, 0] = Z[:, -1] = 1
  15. # Make isles
  16. for i in range(density):
  17. x, y = rand(0, shape[1] // 2) * 2, rand(0, shape[0] // 2) * 2
  18. Z[y, x] = 1
  19. for j in range(complexity):
  20. neighbours = []
  21. if x > 1: neighbours.append((y, x - 2))
  22. if x < shape[1] - 2: neighbours.append((y, x + 2))
  23. if y > 1: neighbours.append((y - 2, x))
  24. if y < shape[0] - 2: neighbours.append((y + 2, x))
  25. if len(neighbours):
  26. y_,x_ = neighbours[rand(0, len(neighbours) - 1)]
  27. if Z[y_, x_] == 0:
  28. Z[y_, x_] = 1
  29. Z[y_ + (y - y_) // 2, x_ + (x - x_) // 2] = 1
  30. x, y = x_, y_
  31. return Z
  32. pyplot.figure(figsize=(10, 5))
  33. pyplot.imshow(maze(80, 40), cmap=pyplot.cm.binary, interpolation='nearest')
  34. pyplot.xticks([]), pyplot.yticks([])
  35. pyplot.show()

comments powered by Disqus