forked from joangoma/ap2-cinebus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdemo.py
362 lines (277 loc) · 10.5 KB
/
demo.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
from rich import emoji
from rich.console import Console
from rich.markdown import Markdown
from rich.panel import Panel
from rich.prompt import Prompt
from rich.style import Style
from rich.table import Table
from buses import *
from billboard import *
from city import *
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
console = Console()
# Function to draw the menu
def draw_menu():
"""Shows the main menu."""
console.clear()
MARKDOWN = """
# CINE BUS 🚌 🎥
## Autors: Laia Mogas i Joan Gomà
"""
md = Markdown(MARKDOWN)
console.print(md)
options = [
"1 Show billboard",
"2 Find film",
"3 Show buses graph",
"4 Show city graph",
"5 Choose film and go to the cinema",
"6 Exit",
]
console.print()
console.print(
Panel(
"\n".join(options),
title="Options:",
expand=False,
border_style="cyan",
),
)
def show_projections(projections: list[Projection]) -> None:
"""Show a set of films to the user"""
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Cinema", justify="left")
table.add_column("Pel·lícula")
table.add_column("Durada")
table.add_column("Horari")
time = 18
for i, projection in enumerate(sorted(projections, key=lambda x: x.time)):
table.add_row(
projection.cinema.name,
projection.film.title,
str(projection.duration),
"{:<02d}".format(projection.time[0])
+ ":"
+ "{:<02d}".format(projection.time[1]),
)
console.print("\nCartellera en horari no decreixent:\n")
console.print(table)
def search_billboard(billboard: Billboard) -> None:
"""Show the films that fulfill the given constraints by the user"""
key = Prompt.ask(
"Filter film by ",
choices=["title", "starting time", "duration"],
)
projections: list[Projection] = list()
if key == "title":
word = Prompt.ask("Introduce the title of the film.")
projections = billboard.search_projection_by_word(word)
if key == "starting time":
hour, minute = get_valid_time(
"Introduce the time from which you can see the film."
)
projections = billboard.search_projection_by_time((hour, minute))
if key == "duration":
durada = get_valid_duration()
projections = billboard.search_projection_by_duration(durada)
show_projections(projections)
def show_film_titles(
billboard: Billboard, osmx_g: OsmnxGraph, city_g: CityGraph
) -> None:
"""Show all film titles from the films that are available."""
for title in billboard.films_titles:
console.print(title.capitalize())
Prompt.ask("\nPress enter to continue...")
search_closest_cinema(billboard, osmx_g, city_g)
def get_valid_duration() -> int:
"""Returns the time input given by the user."""
try:
durada = int(
Prompt.ask("""Introduce the maximimum duration of the film you
want to watch""")
)
return durada
except Exception as error:
console.print("An error ocurred: ", type(error).__name__)
return get_valid_duration()
def get_valid_film_title(billboard: Billboard) -> str | None:
"""Returns the title given by the user, in case it's from a film
that exists.
"""
film = Prompt.ask("Introduce the film you want to see")
if film.lower() not in billboard.films_titles:
Prompt.ask("This film does not exist, press enter to continue")
console.clear()
return None
return film
def get_valid_coordinates() -> Coord:
"""Asks the user their current coordinates and, if well introduced, they
are returned. Otherwise the user is asked again"""
ubi = Prompt.ask(
"Introduce your location (latitude, longitude) ex: 41.38173, 2.12550"
)
try:
ubi = ubi.split(",")
lat, long = float(ubi[0]), float(ubi[1])
return lat, long
except Exception as error:
console.print("An error ocurred: ", type(error).__name__)
Prompt.ask("Please, enter the correct format, press enter to continue")
return get_valid_coordinates()
def get_valid_time(question: str) -> tuple[int, int]:
"""Asks the time they want to leave. If it's given in a correct format
it's returned. Otherwise, the user is asked again"""
leave_time = Prompt.ask("{0}, ex: 19:30".format(question))
try:
hour, minute = leave_time.split(":")
leaving_time: tuple[int, int] = (int(hour), int(minute))
return leaving_time
except Exception as error:
console.print("An error ocurred: ", type(error).__name__)
Prompt.ask("Please, enter the correct format, press enter to continue")
return get_valid_time(question)
def get_valid_option(valid_opt_l: int) -> int:
"""Asks the time they want to leave. If it's given in a correct format
it's returned. Otherwise the user is asked again.
"""
try:
num_projection = int(
Prompt.ask("Choose the projection that you like!")
)
if num_projection > valid_opt_l or num_projection <= 0:
Prompt.ask("Please, enter a valid option, press enter to continue")
return get_valid_option(valid_opt_l)
else:
return num_projection
except Exception as error:
console.print("An error ocurred: ", type(error).__name__)
Prompt.ask("Please, enter the correct format, press enter to continue")
return get_valid_option(valid_opt_l)
def get_valid_projections(
billboard: Billboard, osmx_g: OsmnxGraph,
city_g: CityGraph) -> list[tuple[Projection, Path]] | None:
"""Returns a list of all the projections of a given film that you
can arrive given a starting time"""
film = get_valid_film_title(billboard)
if film is None:
return None
else:
starting_coord: Coord = get_valid_coordinates()
leaving_time: tuple[int, int] = get_valid_time(
"At which time do you want to leave?"
)
projections = billboard.search_projection_by_time(leaving_time)
valid_projections: list[tuple[Projection, Path]] = list()
for projection in projections:
if projection.film.title.lower() != film:
continue
path = find_path(
osmx_g, city_g, starting_coord,
CINEMAS_LOCATION[projection.cinema.name]
)
if path[1] <= calculate_time(leaving_time, projection.time):
valid_projections.append((projection, path))
return valid_projections
def show_find_closest_cinema_menu() -> None:
"""Shows the menu from 5th option (choose a cinema)."""
console.clear()
options = ["1 Show films available", "2 Choose film", "3 Exit"]
console.print(
Panel(
"\n".join(options),
title="Options:",
expand=False,
border_style="cyan3",
)
)
def show_projections_path_info(
valid_projections: list[tuple[Projection, Path]]
) -> None:
"""Shows in a table the possible projections given the user constraints and
the time to get there"""
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Num")
table.add_column("Cinema", justify="left")
table.add_column("Projection time")
table.add_column("Time to get there")
for i, (projection, path) in enumerate(valid_projections):
table.add_row(
str(i + 1),
projection.cinema.name,
"starts at {0}:{1}".format(projection.time[0], projection.time[1]),
"{0} minutes".format(str(round(path[1], 1))),
)
console.print("\nCartellera en horari creixent en temps d'arribada\n")
console.print(table)
def search_closest_cinema(
billboard: Billboard, osmx_g: OsmnxGraph, city_g: CityGraph
) -> None:
"""Driver code of the funcionality about finding the closest cinema
from a given position, film and schedule."""
show_find_closest_cinema_menu()
key = Prompt.ask("Select the option that you want")
if key == "1":
show_film_titles(billboard, osmx_g, city_g)
elif key == "2":
valid_projections: list[
tuple[Projection, Path]
] | None = get_valid_projections(billboard, osmx_g, city_g)
# Wrong title
if valid_projections is None:
search_closest_cinema(billboard, osmx_g, city_g)
# No matching projections
elif len(valid_projections) == 0:
Prompt.ask(
"""Sorry, there are no projections available
given these constraints"""
)
search_closest_cinema(billboard, osmx_g, city_g)
else:
valid_projections.sort(key=lambda p: p[1][1])
show_projections_path_info(valid_projections)
num_projection = get_valid_option(len(valid_projections))
plot_path(city_g, valid_projections[num_projection - 1][1],
"path.png")
path_img = mpimg.imread('path.png')
plt.imshow(path_img)
plt.show()
elif key == "3":
draw_menu()
else:
search_closest_cinema(billboard, osmx_g, city_g)
def handle_input(key: str, billboard: Billboard, buses_g: BusesGraph,
osmx_g: OsmnxGraph, city_g: CityGraph) -> None:
"""Function that handles user input."""
if key == "1":
show_projections(billboard.projections)
elif key == "2":
search_billboard(billboard)
elif key == "3":
show_buses(buses_g)
elif key == "4":
show_city(city_g)
elif key == "5":
search_closest_cinema(billboard, osmx_g, city_g)
Prompt.ask("\nPress enter to return to the main page")
def main() -> None:
"""Driver Code."""
billboard: Billboard = read_billboard()
buses_g: BusesGraph = get_buses_graph()
osmx_g: OsmnxGraph = get_osmnx_graph()
city_g: CityGraph = build_city_graph(osmx_g, buses_g)
while True:
draw_menu()
key = Prompt.ask("Select a valid option")
if key == "6":
console.print(
Panel(
"""See you soon! 👋 \nPlease rate our app in:
https://newskit.social/blog/posts/cinebusfeedback""",
expand=False,
),
)
return
handle_input(key, billboard, buses_g, osmx_g, city_g)
if __name__ == "__main__":
main()