Advertisement
Guest User

Untitled

a guest
Jun 5th, 2017
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. def make_random_caves(width, height):
  2. '''Generate a random cave map.'''
  3. WALL = '#'
  4. EMPTY = ' '
  5.  
  6. def eat_away(mapgrid, start:position):
  7. '''Recursively eat away tunnels.
  8.  
  9. This works by consuming 2-cell mini-segments, then moving to
  10. the end of the 2-cell segment and recursing. The 2-cell spacing
  11. is enough to allow for a corridor, a turn, and then (2 cells) move
  12. past the wall that defines the corridor. Effectively, this means
  13. that only the odd (or even) cells will be eaten, with the walls
  14. being those cells of opposite parity.
  15.  
  16. At each node (intersection?), all 4 cardinal directions are tried,
  17. starting at a random point in the cycle. Because the recursion happens
  18. at the end of each direction, recursive eating may cause a direction
  19. to be blocked when the recursion returns and the direction cycle
  20. advances to point that way.
  21.  
  22. Consider:
  23.  
  24. #####
  25. #2.3#
  26. #.#.#
  27. #1#4#
  28. #####
  29.  
  30. In this example, eating starts at 1, eats a segment north, and
  31. recurses. At 2, the random direction is east, so a segment is
  32. consumed. At 3, the random direction is south, a segment is consumed,
  33. and we recurse to 4. Assuming the grid was only 5x5, there is no place
  34. that can be eaten from 4, since all 4 directions are either off-limits
  35. or already cleared. When the recursion returns to point 1, it might
  36. consider moving east to point 4, but because that cell is already
  37. cleared it will do nothing and return.
  38. '''
  39.  
  40. # List of directions to try, randomly rotated.
  41. try_dirs = (direction.WEST, direction.EAST,
  42. direction.SOUTH, direction.NORTH)
  43. start_dir = random.randrange(len(try_dirs))
  44. try_dirs = try_dirs[start_dir:] + try_dirs[:start_dir]
  45.  
  46. for dirn in try_dirs:
  47. dv = dirn.vector
  48. p1 = start + dv
  49. p2 = start + 2 * dv
  50.  
  51. if p2 not in mapgrid:
  52. # might go past the border - don't.
  53. continue
  54.  
  55. if any(mapgrid[p] != WALL for p in (p1, p2)):
  56. # might already have a tunnel - don't connect them.
  57. continue
  58.  
  59. for p in (p1, p2):
  60. mapgrid[p] = EMPTY
  61.  
  62. eat_away(mapgrid, p2)
  63.  
  64. mapgrid = grid(width=width, height=height, fill=WALL)
  65. eat_away(mapgrid, position(1, 1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement