dungeon.py
2776 bytes | 7bd8729
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | """ Procedural Dungeon Generation for Dungeon Descent """ import random class DungeonMap: def __init__(self, width=20, height=10): self.width = width self.height = height # Fill with walls self.tiles = [["#" for _ in range(width)] for _ in range(height)] self.rooms = [] def generate(self): """Create a random dungeon with rooms and corridors""" num_rooms = random.randint(3, 5) for _ in range(num_rooms): w = random.randint(3, 6) h = random.randint(3, 4) x = random.randint(1, self.width - w - 1) y = random.randint(1, self.height - h - 1) new_room = (x, y, w, h) # Check for overlap overlap = False for other_room in self.rooms: if self.intersects(new_room, other_room): overlap = True break if not overlap: self.create_room(new_room) if len(self.rooms) > 0: # Connect to previous room prev_x, prev_y, prev_w, prev_h = self.rooms[-1] self.create_h_tunnel(prev_x + prev_w//2, x + w//2, prev_y + prev_h//2) self.create_v_tunnel(prev_y + prev_h//2, y + h//2, x + w//2) self.rooms.append(new_room) # Place player in first room if self.rooms: rx, ry, rw, rh = self.rooms[0] start_pos = (rx + rw//2, ry + rh//2) return start_pos return (1, 1) def intersects(self, r1, r2): x1, y1, w1, h1 = r1 x2, y2, w2, h2 = r2 return (x1 < x2 + w2 and x1 + w1 > x2 and y1 < y2 + h2 and y1 + h1 > y2) def create_room(self, room): x, y, w, h = room for i in range(x, x + w): for j in range(y, y + h): self.tiles[j][i] = "." def create_h_tunnel(self, x1, x2, y): for x in range(min(x1, x2), max(x1, x2) + 1): self.tiles[y][x] = "." def create_v_tunnel(self, y1, y2, x): for y in range(min(y1, y2), max(y1, y2) + 1): self.tiles[y][x] = "." def render(self, player_pos): output = [] for y in range(self.height): row = [] for x in range(self.width): if (x, y) == player_pos: row.append("@") else: row.append(self.tiles[y][x]) output.append(" ".join(row)) return "\n".join(output) def is_walkable(self, x, y): if 0 <= x < self.width and 0 <= y < self.height: return self.tiles[y][x] == "." return False |
GIMHub