105 lines
2.8 kB
1"""Command-line entry point handling."""
2
3import argparse
4import sys
5from dataclasses import dataclass
6
7from .errors import FlyInError
8from .flow.scheduler import Scheduler
9from .parser import MapParser
10from .render.base import Broadcast, Renderer
11from .render.text import ColorTextRenderer
12from .simulation import Simulation
13
14
15@dataclass(frozen=True)
16class Options:
17 """What the command line asked for.
18
19 Attributes:
20 map_file: Path of the map to fly.
21 visual: Whether to open the graphical view as well.
22 color: Whether the printed lines may carry color.
23 """
24
25 map_file: str
26 visual: bool
27 color: bool
28
29
30def parse_options(argv: list[str]) -> Options:
31 """Read the command line.
32
33 Args:
34 argv: Arguments, excluding the program name.
35
36 Returns:
37 The options asked for.
38 """
39 parser = argparse.ArgumentParser(
40 prog="python -m src",
41 description="Fly a fleet of drones across a map of zones."
42 )
43 parser.add_argument("map_file", help="map file to read")
44 parser.add_argument(
45 "--visual",
46 action="store_true",
47 help="open a graphical view of the run as well"
48 )
49 parser.add_argument(
50 "--no-color",
51 action="store_true",
52 help="print the turns without color"
53 )
54 parsed = parser.parse_args(argv)
55 return Options(
56 map_file=str(parsed.map_file),
57 visual=bool(parsed.visual),
58 color=not bool(parsed.no_color)
59 )
60
61
62def build_view(options: Options) -> Renderer:
63 """Assemble the views the run will be shown.
64
65 The graphical view is imported only when it is wanted, so the
66 program still runs on a machine where pygame is missing.
67
68 Args:
69 options: What the command line asked for.
70
71 Returns:
72 The view to hand the simulation.
73
74 Raises:
75 FlyInError: If the graphical view was asked for and pygame is
76 not installed.
77 """
78 text = ColorTextRenderer(enabled=None if options.color else False)
79 if not options.visual:
80 return text
81 try:
82 from .render.pygame_view import PygameView
83 except ImportError as err:
84 raise FlyInError(f"the graphical view needs pygame: {err}") from err
85 return Broadcast(text, PygameView())
86
87
88def main(argv: list[str]) -> int:
89 """Run the simulator.
90
91 Args:
92 argv: Command-line arguments, excluding the program name.
93
94 Returns:
95 Process exit code, 0 on success.
96 """
97 options = parse_options(argv)
98 try:
99 scenario = MapParser(options.map_file).parse()
100 schedule = Scheduler(scenario).solve()
101 Simulation(scenario, schedule).run(build_view(options))
102 except FlyInError as err:
103 print(f"error: {err}", file=sys.stderr)
104 return 1
105 return 0