This repository has been archived by the owner on Jan 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
City.py
269 lines (197 loc) · 8.16 KB
/
City.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
"""
A City is a graph made of Buildings (nodes) which are connected by Streets (arcs)
"""
from typing import Callable, List, Tuple, Union, Dict
import traceback
import pygame
from PygameSettings import *
from Building import Building
from Street import Street
class City:
def __init__(
self,
buildings: List[Building],
on_change: Callable[[], None],
create_streets_between_buildings: bool = True
) -> None:
self.buildings = buildings
self.streets: List[Street] = []
self.on_change = on_change
self.highlighted_building = None
if create_streets_between_buildings:
self.create_streets_between_buildings()
def draw(self, screen: pygame.Surface) -> None:
for street in self.streets:
street.draw(screen)
for building in self.buildings:
building.draw(screen)
for street in self.streets:
if street.show_arrows:
street.draw_arrow(screen)
if self.highlighted_building is not None:
self.draw_highlight(screen)
# Assume building is not being highlighted at next frame
self.highlighted_building.annotate_with_text = False
def set_highlighted_building(self, mouse_pos: Tuple[int, int]) -> None:
# Check if there is a building at given pos
building = self.get_building_at_pos(mouse_pos)
if building is not None:
# self.highlighted_building = Building(*building.rect.topleft, connections=[], annotate_with_text=False)
self.highlighted_building = building
self.highlighted_building.annotate_with_text = True
else:
self.highlighted_building = None
def draw_highlight(self, screen: pygame.Surface) -> None:
highlight_rect = pygame.Rect(
self.highlighted_building.rect.topleft,
(
self.highlighted_building.rect.width * 1.1,
self.highlighted_building.rect.height * 1.1
)
)
# Center highlight on the hovered building
highlight_rect.centerx, highlight_rect.centery = self.highlighted_building.rect.center
pygame.draw.ellipse(
screen,
Colors.LIGHT_BLUE,
highlight_rect
)
def get_building_at_pos(self, pos: Tuple[int, int]) -> Union[Building, None]:
"""
Returns building at given position, if any exists. Otherwise returns None
"""
for building in self.buildings:
if pos[0] - NODE_RADIUS < building.x < pos[0] + NODE_RADIUS:
if pos[1] - NODE_RADIUS < building.y < pos[1] + NODE_RADIUS:
return building
def create_building(self, pos: Tuple[int, int]) -> None:
"""
Creates a building at the given position
"""
new_building_pos = (pos[0] - NODE_RADIUS//4, pos[1] - NODE_RADIUS//4)
new_building = Building(*new_building_pos, connections=[], annotate_with_text=False)
self.buildings.append(new_building)
self.on_change()
def _remove_connections(self, building_to_remove: Building) -> None:
"""
Removes all connections to / from given building
"""
# Remove connections FROM building_to_delete
for connected_building in building_to_remove.connections:
try:
# BUG: sometimes getting error ('list.remove(x): x not in list')
connected_building.connections.remove(building_to_remove)
except ValueError:
traceback.print_exc()
# Remove connections TO building_to_delete
for potentailly_connected_building in self.buildings:
try:
if building_to_remove in potentailly_connected_building.connections:
potentailly_connected_building.connections.remove(
building_to_remove)
except ValueError:
traceback.print_exc()
def remove_building(self, pos: Tuple[int, int]) -> None:
"""
Removes building at given position (if any exists) and cuts off all connections
to / from it
"""
building_to_remove = self.get_building_at_pos(pos)
if building_to_remove is None:
print(f"No building to remove at {pos}")
return
self._remove_connections(building_to_remove)
self.buildings.remove(building_to_remove)
# REFACTOR
# IMPORTANT: This may cause performance issues in large maps
# This resets the streets list after any buildings are removed in order to keep from having 'floating' streets
# for _ in range(len(self.streets)):
# del self.streets[0]
self.streets.clear()
self.create_streets_between_buildings()
self.on_change()
def connect_buildings(
self,
pos1: Tuple[int, int],
pos2: Tuple[int, int],
bidirectional=False,
verbose=True
) -> None:
"""
Create a connection between nodes at pos1 and pos2
"""
building1 = self.get_building_at_pos(pos1)
building2 = self.get_building_at_pos(pos2)
if building1 is None or building2 is None:
print(
f"Couldn't find one of the buildings: {building1}, {building2}")
return
# TODO: check whether building are already connected before doing this step
# Connect first to second
building1.connections.append(building2)
self.draw_street(building1, building2)
if bidirectional:
# Connect second to first as well
building2.connections.append(building1)
self.draw_street(building1, building2)
self.on_change()
if verbose:
print(f"Connected two buildings together at {pos1} and {pos2}")
print(f"First building connections: {building1.connections}")
print(f"Second building connections: {building2.connections}")
def create_streets_between_buildings(self) -> None:
"""
Creates directed Arcs between all connected buildings
"""
# BUG: Bi-directional connections aren't being drawn until the map is reloaded
# NOTE: above bug is because bi-connections aren't being setup properly in this method
for building in self.buildings:
for connected_building in building.connections:
self.streets.append(
Street(
building, connected_building, color=Colors.BLACK, width=1
)
)
def draw_street(
self,
building1: Building,
building2: Building,
color: Colors = Colors.BLACK,
width: int = 1
) -> None:
"""
Creates an Arc between the two given buildings
"""
new_street = Street(building1, building2, color=color, width=width)
self.streets.append(new_street)
def color_paths(self, nodes: List[Building]) -> None:
"""
Colors a path starting from first node until last node in the
given list
"""
for node1, node2 in zip(nodes[:-1], nodes[1:]):
self.draw_street(node1, node2, Colors.YELLOW, width=3)
@staticmethod
def make_buildings_from_saved_file(
building_data: Dict[str, List]
) -> List[Building]:
buildings: List[Building] = []
# First, create buildings without their connections
for building_data in building_data["data"]:
buildings.append(
Building(**building_data, annotate_with_text=False)
)
# then connect them all
temp_city = City(
buildings,
on_change=lambda: None,
create_streets_between_buildings=False
)
def get_building_at_pos(x, y):
return temp_city.get_building_at_pos((x, y))
# Convert each building's connections from coordinates to Building objects
for building in buildings:
building.connections = [
get_building_at_pos(*coords) for coords in building.connections
]
return buildings