-
Notifications
You must be signed in to change notification settings - Fork 0
/
procgen.py
299 lines (228 loc) · 8.89 KB
/
procgen.py
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
from __future__ import annotations
import random
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Tuple
import numpy as np
import scipy.signal # type: ignore
import tcod
import entity_factories
import noise_factories
import tile_types
from game_map import GameMap
from snow_map import SnowMap
# import numpy as np
if TYPE_CHECKING:
from numpy.typing import NDArray
from engine import Engine
from entity import Entity
# (floor number, number of items/monsters)
# TODO: Replace this with normal spawning as the player will mostly be on one map.
max_items_by_floor = [
(1, 1),
(4, 2),
]
max_monsters_by_floor = [
(1, 2),
(4, 3),
(6, 5),
]
# {floor: [(entity, weight)]}
item_chances: Dict[int, List[Tuple[Entity, int]]] = {
0: [(entity_factories.health_potion, 35)],
2: [(entity_factories.confusion_scroll, 10)],
4: [(entity_factories.lightning_scroll, 25), (entity_factories.sword, 5)],
6: [(entity_factories.fireball_scroll, 25), (entity_factories.chain_mail, 15)],
}
enemy_chances: Dict[int, List[Tuple[Entity, int]]] = {
0: [(entity_factories.orc, 80)],
3: [(entity_factories.troll, 15)],
5: [(entity_factories.troll, 30)],
7: [(entity_factories.troll, 60)],
}
INITIAL_CHANCE = 0.42 # Initial wall chance.
INITIAL_RANGE = INITIAL_CHANCE / 2
INITIAL_MIN = 0.5 - INITIAL_RANGE
INITIAL_MAX = 0.5 + INITIAL_RANGE
def get_max_value_for_floor(
max_value_by_floor: List[Tuple[int, int]], floor: int
) -> int:
current_value = 0
for floor_minimum, value in max_value_by_floor:
if floor_minimum > floor:
break
else:
current_value = value
return current_value
def get_entities_at_random(
weighted_chances_by_floor: Dict[int, List[Tuple[Entity, int]]],
number_of_entities: int,
floor: int,
) -> List[Entity]:
entity_weighted_chances = {}
for key, values in weighted_chances_by_floor.items():
if key > floor:
break
else:
for value in values:
entity = value[0]
weighted_chance = value[1]
entity_weighted_chances[entity] = weighted_chance
entities = list(entity_weighted_chances.keys())
entity_weighted_chance_values = list(entity_weighted_chances.values())
chosen_entities = random.choices(
entities, weights=entity_weighted_chance_values, k=number_of_entities
)
return chosen_entities
class RectangularRoom:
def __init__(self, x: int, y: int, width: int, height: int):
self.x1 = x
self.y1 = y
self.x2 = x + width
self.y2 = y + height
@property
def center(self) -> Tuple[int, int]:
center_x = int((self.x1 + self.x2) / 2)
center_y = int((self.y1 + self.y2) / 2)
return center_x, center_y
@property
def inner(self) -> Tuple[slice, slice]:
"""Return the inner area of this room as a 2D array index."""
return slice(self.x1 + 1, self.x2), slice(self.y1 + 1, self.y2)
def intersects(self, other: RectangularRoom) -> bool:
"""Return True if this room overlaps with another RectangularRoom."""
return (
self.x1 <= other.x2
and self.x2 >= other.x1
and self.y1 <= other.y2
and self.y2 >= other.y1
)
def place_entities(
room: RectangularRoom,
dungeon: GameMap,
floor_number: int,
) -> None:
number_of_monsters = random.randint(
0, get_max_value_for_floor(max_monsters_by_floor, floor_number)
)
number_of_items = random.randint(
0, get_max_value_for_floor(max_items_by_floor, floor_number)
)
monsters: List[Entity] = get_entities_at_random(
enemy_chances, number_of_monsters, floor_number
)
items: List[Entity] = get_entities_at_random(
item_chances, number_of_items, floor_number
)
for entity in monsters + items:
x = random.randint(room.x1 + 1, room.x2 - 1)
y = random.randint(room.y1 + 1, room.y2 - 1)
if not any(entity.x == x and entity.y == y for entity in dungeon.entities):
entity.spawn(dungeon, x, y)
def tunnel_between(
start: Tuple[int, int], end: Tuple[int, int]
) -> Iterator[Tuple[int, int]]:
"""Return an L-shaped tunnel between these two points."""
x1, y1 = start
x2, y2 = end
if random.random() < 0.5: # a 50% chance.
# Move horizontally, then vertically.
corner_x, corner_y = x2, y1
else:
# Move vertically, then horizontally.
corner_x, corner_y = x1, y2
# Generate the coordinates for this tunnel.
for x, y in tcod.los.bresenham((x1, y1), (corner_x, corner_y)).tolist():
yield x, y
for x, y in tcod.los.bresenham((corner_x, corner_y), (x2, y2)).tolist():
yield x, y
def generate_dungeon(
max_rooms: int,
room_min_size: int,
room_max_size: int,
map_width: int,
map_height: int,
engine: Engine,
) -> GameMap:
"""Generate a new dungeon map."""
player = engine.player
dungeon = GameMap(engine, map_width, map_height, entities=[player])
dungeon.tiles[:] = tile_types.wall
rooms: List[RectangularRoom] = []
center_of_last_room = (0, 0)
for _ in range(max_rooms):
room_width = random.randint(room_min_size, room_max_size)
room_height = random.randint(room_min_size, room_max_size)
x = random.randint(0, dungeon.width - room_width - 1)
y = random.randint(0, dungeon.height - room_height - 1)
# "RectangularRoom" class makes rectangles easier to work with.
new_room = RectangularRoom(x, y, room_width, room_height)
# Run through the other rooms and see if they intersect with this one.
if any(new_room.intersects(other_room) for other_room in rooms):
continue # This room intersects, so go to the next attempt.
# If there are no intersections then the room is valid.
# Dig out this room's inner area.
dungeon.tiles[new_room.inner] = tile_types.floor
if len(rooms) == 0:
# The first room, where the player starts.
player.place(*new_room.center, dungeon)
else: # All rooms after the first.
# Dig out a tunnel between this room and the previous one.
for x, y in tunnel_between(rooms[-1].center, new_room.center):
dungeon.tiles[x, y] = tile_types.floor
center_of_last_room = new_room.center
place_entities(new_room, dungeon, engine.game_world.current_floor)
dungeon.tiles[center_of_last_room] = tile_types.down_stairs
dungeon.downstairs_location = center_of_last_room
# Finally, append the new room to the list.
rooms.append(new_room)
return dungeon
def convolve(tiles: NDArray[Any], wall_rule: int = 5) -> NDArray[np.bool_]:
"""
from: https://github.com/libtcod/python-tcod/blob/main/examples/cavegen.py
Return the next step of the cave generation algorithm.
`tiles` is the input array. (0: wall, 1: floor)
If the 3x3 area around a tile (including itself) has `wall_rule` number of
walls then the tile will become a wall.
"""
# Use convolve2d, the 2nd input is a 3x3 ones array.
neighbors: NDArray[Any] = scipy.signal.convolve2d(
tiles == 0, [[1, 1, 1], [1, 1, 1], [1, 1, 1]], "same"
)
next_tiles: NDArray[np.bool_] = neighbors < wall_rule # Apply the wall rule.
return next_tiles
def generate_overworld(
map_width: int,
map_height: int,
engine: Engine,
) -> GameMap:
"""Generate a new dungeon map."""
player = engine.player
dungeon = GameMap(engine, map_width, map_height, entities=[player])
snow_map = SnowMap(map_width, map_height)
noise_map = noise_factories.noise_simplex_fbm[
tcod.noise.grid(shape=(map_width, map_height), scale=0.25, indexing="xy")
].transpose()
noise_map = (noise_map + 1) * 0.5
tree_map: NDArray[np.bool_] = np.all(
[noise_map <= INITIAL_MAX, noise_map >= INITIAL_MIN], axis=0
)
tree_map = convolve(tree_map, wall_rule=6)
# Set tiles to `tile_types.tree` where `tree_map` is False
dungeon.tiles[~tree_map] = tile_types.tree
# Find all floor tiles
floor_coords = np.transpose(np.where(dungeon.tiles == tile_types.floor))
floor_coords = np.ravel_multi_index(floor_coords.T, dungeon.tiles.shape)
dungeon.tiles[
tree_map
] = (
tile_types.ground
) # Turn all non tree tiles into ground tiles. Since, by default they are floor tiles.
snow_map.set_snow_levels(dungeon, tree_map)
# TODO: Place entities.
# TODO: Place cave entrances.
# ? Chunking should probably go here, then place the player in the starting chunk.
# Select a random floor tile and place the player there
index = np.random.choice(floor_coords)
player_coord = np.unravel_index(index, dungeon.tiles.shape)
player.place(*player_coord, dungeon)
# TODO: Place tent (should be w/in 3 tile radius of player).
return dungeon