1 """ Procedural map generation for levels """
6 i = random.randint(0,100)
17 dist_from_other_rooms = 0
20 region_size_in_tiles = 0
22 def __init__(self, width, height, rooms, min_room_size, max_room_size, dist_from_edge,
23 dist_from_other_rooms, region_size_in_tiles):
24 """ Initialize the level parameters
29 self.min_room_size = min_room_size
30 self.max_room_size = max_room_size
31 self.dist_from_edge = dist_from_edge
32 self.dist_from_other_rooms = dist_from_other_rooms
33 self.region_size_in_tiles = region_size_in_tiles
36 """ Generate a random level map
38 self.generate_regions()
39 row = ['#' for x in range(self.width * self.region_size_in_tiles)]
40 self.map = [row[:] for x in range(self.height * self.region_size_in_tiles)]
41 regions_selected = random.sample(range(self.region), min(self.region, self.rooms))
42 print('Regions: %s' % str(regions_selected))
43 for region in regions_selected:
44 self.generate_room(region)
46 def generate_regions(self):
47 """ Generate a random level region map
49 row = ['#' for x in range(self.width)]
50 self.regions = [row[:] for x in range(self.height)]
51 for h in range(self.height):
52 for w in range(self.width):
53 random_number = random.randint(0, 2)
55 self.regions[h][w] = self.region
60 self.regions[h][w] = self.regions[h][w - 1]
65 self.regions[h][w] = self.region
69 self.regions[h][w] = self.regions[h - 1][w]
71 self.regions[h][w] = self.region
75 self.regions[h][w] = self.regions[h - 1][w]
76 elif random_number > 0:
77 self.regions[h][w] = self.regions[h][w - 1]
79 self.regions[h][w] = self.region
82 def generate_room(self, region_selected):
85 for h in range(self.height):
86 for w in range(self.width):
87 if self.regions[h][w] == region_selected:
89 w_dist = self.dist_from_other_rooms
90 elif self.regions[h][w-1] == region_selected:
93 w_dist = self.dist_from_other_rooms
95 if w + 1 == self.width:
96 e_dist = self.region_size_in_tiles - self.dist_from_other_rooms
97 elif self.regions[h][w+1] == region_selected:
98 e_dist = self.region_size_in_tiles
100 e_dist = self.region_size_in_tiles - self.dist_from_other_rooms
103 n_dist = self.dist_from_other_rooms
104 elif self.regions[h-1][w] == region_selected:
107 n_dist = self.dist_from_other_rooms
109 if h + 1 == self.height:
110 s_dist = self.region_size_in_tiles - self.dist_from_other_rooms
111 elif self.regions[h+1][w] == region_selected:
112 s_dist = self.region_size_in_tiles
114 s_dist = self.region_size_in_tiles - self.dist_from_other_rooms
116 for wt in range(w_dist, e_dist):
117 for ht in range(n_dist, s_dist):
118 self.map[h * self.region_size_in_tiles + ht][w * self.region_size_in_tiles + wt] = ' '
121 file = open('map.txt', 'w')
124 file.write(''.join(l))
127 for l in self.regions:
131 if __name__ == '__main__':
133 level = LevelGenerator(width=8, height=5, rooms=12, min_room_size=5, max_room_size=20,
134 dist_from_edge=2, dist_from_other_rooms=1, region_size_in_tiles=6)
137 input("Press Enter to continue...")