以下是一个示例代码,展示如何使用BSP(二叉空间分区)算法来生成地牢的房间和走廊。该代码可以生成一个简单的地牢,并确保走廊连接所有房间。
import random
class BSPDungeonGenerator:
def __init__(self, width, height, min_room_size, max_room_size):
self.width = width
self.height = height
self.min_room_size = min_room_size
self.max_room_size = max_room_size
self.dungeon = [[0] * width for _ in range(height)]
def generate(self):
self.split_room((0, 0), (self.width - 1, self.height - 1))
self.connect_rooms((0, 0), (self.width - 1, self.height - 1))
def split_room(self, top_left, bottom_right):
width = bottom_right[0] - top_left[0] + 1
height = bottom_right[1] - top_left[1] + 1
if width <= self.max_room_size and height <= self.max_room_size:
# Create a room in the current space
self.create_room(top_left, bottom_right)
else:
# Split the current space into two smaller spaces
if width > height:
# Split horizontally
split_x = random.randint(top_left[0] + self.min_room_size, bottom_right[0] - self.min_room_size)
self.split_room(top_left, (split_x, bottom_right[1]))
self.split_room((split_x + 1, top_left[1]), bottom_right)
else:
# Split vertically
split_y = random.randint(top_left[1] + self.min_room_size, bottom_right[1] - self.min_room_size)
self.split_room(top_left, (bottom_right[0], split_y))
self.split_room((top_left[0], split_y + 1), bottom_right)
def create_room(self, top_left, bottom_right):
for i in range(top_left[0], bottom_right[0] + 1):
for j in range(top_left[1], bottom_right[1] + 1):
self.dungeon[j][i] = 1
def connect_rooms(self, top_left, bottom_right):
for i in range(top_left[0] + 1, bottom_right[0]):
self.dungeon[top_left[1]][i] = 1
self.dungeon[bottom_right[1]][i] = 1
for j in range(top_left[1] + 1, bottom_right[1]):
self.dungeon[j][top_left[0]] = 1
self.dungeon[j][bottom_right[0]] = 1
def print_dungeon(self):
for row in self.dungeon:
print(''.join(str(cell) for cell in row))
# 使用示例
generator = BSPDungeonGenerator(10, 10, 3, 6)
generator.generate()
generator.print_dungeon()
这个代码使用BSP算法来递归地将地牢空间划分成较小的空间,直到达到最小房间大小。然后,在每个最小空间内创建一个房间。最后,通过在每个房间之间创建走廊来连接它们。
注意,这个示例代码只是一个简化版本,只生成了一个简单的地牢。如果你想生成更复杂的地牢,你可能需要添加更多的逻辑来处理更多的边缘情况和限制条件。