03 - Refactor room generation (from inside Leaf/tree to the Level class)

This commit is contained in:
kleph 2016-12-07 03:08:49 +01:00
parent e1ee70f495
commit 71641a8ea7

View file

@ -24,7 +24,6 @@ class Leaf:
self.height = h
self.left_leaf = None
self.right_leaf = None
self.room = None
def print_leaf(self):
print('[Leaf]' + str(self.id) + ': (' + str(self.x) + '), (' + str(self.y) + ')' +
@ -63,29 +62,6 @@ class Leaf:
return True
def generate_rooms(self, tilemap):
"""
:return: generate rooms inside partitioned space
"""
if self.left_leaf:
self.left_leaf.generate_rooms(tilemap)
if self.right_leaf:
self.right_leaf.generate_rooms(tilemap)
if not self.left_leaf and not self.right_leaf:
self.room = self.generate_room(tilemap)
def generate_room(self, tilemap):
# Leave space for walls
x = random.randint(self.x+1, self.x+2)
y = random.randint(self.y+1, self.y+2)
w = random.randint(MIN_LEAF_SIZE / 2, self.width-2)
h = random.randint(MIN_LEAF_SIZE / 2, self.height-2)
r = Room(x, y, w, h, self.id)
r.draw_map(tilemap)
return r
class Room:
""" room """
@ -128,7 +104,10 @@ class Level:
self.tilemap = []
if tile_file:
self.load_tileset(tile_file)
self.tree = self.generate_tree()
self.tree = None
self.rooms = []
self.regenerate()
def load_tileset(self, tile_file):
resource_file = open(tile_file)
@ -151,13 +130,44 @@ class Level:
tree.append(l.left_leaf)
tree.append(l.right_leaf)
return tree
def generate_rooms(self, leaf, tilemap, room_list):
"""
generate rooms inside partitioned space
:return: a list of generated rooms
"""
if leaf.left_leaf:
self.generate_rooms(leaf.left_leaf, tilemap, room_list)
if leaf.right_leaf:
self.generate_rooms(leaf.right_leaf, tilemap, room_list)
if not leaf.left_leaf and not leaf.right_leaf:
room = self.generate_room(leaf, tilemap)
room_list.append(room)
return room_list
def generate_room(self, leaf, tilemap):
# Leave space for walls
x = random.randint(leaf.x + 1, leaf.x + 2)
y = random.randint(leaf.y + 1, leaf.y + 2)
w = random.randint(MIN_LEAF_SIZE / 2, leaf.width - 2)
h = random.randint(MIN_LEAF_SIZE / 2, leaf.height - 2)
r = Room(x, y, w, h, leaf.id)
r.draw_map(tilemap)
return r
def regenerate(self):
"""" generate a new level """
self.tree = self.generate_tree()
# initialize tilemap with road/ground
self.tilemap = [[self.TILE_ROAD for y in range(0, self.sizey)] for x in range(0, self.sizex)]
# create rooms from partitions
tree[0].generate_rooms(self.tilemap)
return tree
self.rooms = self.generate_rooms(self.tree[0], self.tilemap, [])
def draw_map(self):
for y in range(0, self.sizey):
@ -170,6 +180,7 @@ class Level:
print(self.tilemap[x][y], end="")
print("")
##
# main
##
@ -187,7 +198,7 @@ def on_key_press(symbol, modifiers):
print('Will quit')
if symbol == key.R:
print('Regeneration')
level.generate_tree()
level.regenerate()
window.invalid = True
if symbol == key.D:
level.dump_tilemap()