Skip to content
Snippets Groups Projects
Commit 198a28f8 authored by Muhamed (aider)'s avatar Muhamed (aider)
Browse files

refactor: Verbessere Rover-Integration und Fehlerbehandlung in Terminal-UI

parent d2e08ece
No related branches found
No related tags found
No related merge requests found
...@@ -14,14 +14,21 @@ def main(): ...@@ -14,14 +14,21 @@ def main():
try: try:
# Erstelle einen Rover und MissionControl # Erstelle einen Rover und MissionControl
rover = Rover(0, 0, 0) # Startposition (0,0) mit Richtung 0 (Nord) rover = Rover(0, 0, 0) # Startposition (0,0) mit Richtung 0 (Nord)
rover.set_plateau_size(20, 20) # Setze Plateau-Größe
# Setze Plateau-Größe falls möglich
if hasattr(rover, 'set_plateau_size'):
rover.set_plateau_size(20, 20)
mission_control = MissionControl(rover, 20, 20) mission_control = MissionControl(rover, 20, 20)
# Füge einige Test-Hindernisse hinzu # Füge einige Test-Hindernisse hinzu
mission_control.add_obstacle(5, 5) try:
mission_control.add_obstacle(10, 8) mission_control.add_obstacle(5, 5)
mission_control.add_obstacle(15, 12) mission_control.add_obstacle(10, 8)
mission_control.add_obstacle(15, 12)
print("Test-Hindernisse hinzugefügt.")
except Exception as e:
print(f"Warnung: Konnte Hindernisse nicht hinzufügen: {e}")
print("Mission Control initialisiert.") print("Mission Control initialisiert.")
print("Starte Terminal-UI...") print("Starte Terminal-UI...")
...@@ -31,8 +38,15 @@ def main(): ...@@ -31,8 +38,15 @@ def main():
except KeyboardInterrupt: except KeyboardInterrupt:
print("\nProgramm durch Benutzer beendet.") print("\nProgramm durch Benutzer beendet.")
except ImportError as e:
print(f"Import-Fehler: {e}")
print("Stellen Sie sicher, dass alle benötigten Module verfügbar sind.")
print("Installieren Sie ncurses mit: pip install windows-curses")
sys.exit(1)
except Exception as e: except Exception as e:
print(f"Fehler beim Starten der Terminal-UI: {e}") print(f"Fehler beim Starten der Terminal-UI: {e}")
import traceback
traceback.print_exc()
sys.exit(1) sys.exit(1)
if __name__ == "__main__": if __name__ == "__main__":
......
...@@ -17,18 +17,25 @@ class MissionControl: ...@@ -17,18 +17,25 @@ class MissionControl:
if rover is None: if rover is None:
# Wenn kein Rover übergeben wurde, erstelle einen Standard-Rover # Wenn kein Rover übergeben wurde, erstelle einen Standard-Rover
self.rover = Rover(0, 0, 0) self.rover = Rover(0, 0, 0)
self.rover.set_plateau_size(plateau_size_x, plateau_size_y) if hasattr(self.rover, 'set_plateau_size'):
self.rover.set_plateau_size(plateau_size_x, plateau_size_y)
else: else:
self.rover = rover self.rover = rover
self.plateau_size_x = plateau_size_x self.plateau_size_x = plateau_size_x
self.plateau_size_y = plateau_size_y self.plateau_size_y = plateau_size_y
# Initialisiere Mars mit einem Plateau # Initialisiere Mars mit einem Plateau (falls verfügbar)
from mars import Mars try:
from plateau import Plateau from mars import Mars
plateau = Plateau(self.plateau_size_x, self.plateau_size_y) from plateau import Plateau
self.mars = Mars(plateau) plateau = Plateau(self.plateau_size_x, self.plateau_size_y)
self.mars = Mars(plateau)
except ImportError:
# Fallback: Erstelle eine einfache Map
from map import Map
self.map = Map(self.plateau_size_x, self.plateau_size_y)
self.mars = None
def send_commands(self, cmd: str) -> str: def send_commands(self, cmd: str) -> str:
""" """
...@@ -80,12 +87,17 @@ class MissionControl: ...@@ -80,12 +87,17 @@ class MissionControl:
x: Die x-Koordinate des Hindernisses x: Die x-Koordinate des Hindernisses
y: Die y-Koordinate des Hindernisses y: Die y-Koordinate des Hindernisses
""" """
if isinstance(self.rover, Rover): # Füge Hindernis zum Rover hinzu
if isinstance(self.rover, Rover) and hasattr(self.rover, 'add_obstacle'):
self.rover.add_obstacle(x, y) self.rover.add_obstacle(x, y)
# Füge das Hindernis auch zum Mars-Plateau hinzu # Füge das Hindernis auch zum Mars-Plateau hinzu
if hasattr(self.mars, 'plateau') and hasattr(self.mars.plateau, 'add_obstacle'): if self.mars and hasattr(self.mars, 'plateau') and hasattr(self.mars.plateau, 'add_obstacle'):
self.mars.plateau.add_obstacle(x, y) self.mars.plateau.add_obstacle(x, y)
# Fallback: Füge zu direkter Map hinzu
elif hasattr(self, 'map') and hasattr(self.map, 'add_obstacle'):
self.map.add_obstacle(x, y)
def get_feedback(self) -> str: def get_feedback(self) -> str:
""" """
......
...@@ -44,10 +44,32 @@ class TerminalUI: ...@@ -44,10 +44,32 @@ class TerminalUI:
Dictionary mit Rover-Informationen Dictionary mit Rover-Informationen
""" """
rover = self.mission_control.rover rover = self.mission_control.rover
# Versuche verschiedene Attribute für Position
position = (0, 0)
if hasattr(rover, 'x') and hasattr(rover, 'y'):
position = (rover.x, rover.y)
elif hasattr(rover, 'position'):
position = rover.position
# Versuche verschiedene Attribute für Richtung
direction = 'N'
if hasattr(rover, 'direction'):
direction = rover.direction
elif hasattr(rover, 'heading'):
direction = rover.heading
# Status ermitteln
status = 'OK'
if hasattr(rover, 'status'):
status = rover.status
elif hasattr(rover, 'is_blocked') and rover.is_blocked:
status = 'BLOCKED'
return { return {
'position': getattr(rover, 'position', (0, 0)), 'position': position,
'direction': getattr(rover, 'direction', 'N'), 'direction': direction,
'status': getattr(rover, 'status', 'OK') 'status': status
} }
def update_map(self) -> None: def update_map(self) -> None:
...@@ -60,6 +82,17 @@ class TerminalUI: ...@@ -60,6 +82,17 @@ class TerminalUI:
plateau = self.mission_control.mars.plateau plateau = self.mission_control.mars.plateau
if hasattr(plateau, 'set_rover_position'): if hasattr(plateau, 'set_rover_position'):
plateau.set_rover_position(position[0], position[1]) plateau.set_rover_position(position[0], position[1])
# Füge besuchte Position zur Karte hinzu
if hasattr(plateau, 'move'):
plateau.move(position[0], position[1])
# Fallback: Direkte Map-Aktualisierung
elif hasattr(self.mission_control, 'map'):
map_obj = self.mission_control.map
if hasattr(map_obj, 'set_rover_position'):
map_obj.set_rover_position(position[0], position[1])
if hasattr(map_obj, 'move'):
map_obj.move(position[0], position[1])
def draw_ui(self) -> None: def draw_ui(self) -> None:
"""Zeichnet die komplette Benutzeroberfläche mit ncurses.""" """Zeichnet die komplette Benutzeroberfläche mit ncurses."""
...@@ -112,23 +145,45 @@ class TerminalUI: ...@@ -112,23 +145,45 @@ class TerminalUI:
map_height = height - current_line - 4 # Platz für Steuerungshinweise map_height = height - current_line - 4 # Platz für Steuerungshinweise
map_width = width - 4 map_width = width - 4
# Versuche verschiedene Karten-Quellen
map_drawn = False
# 1. Versuche Mars/Plateau
if hasattr(self.mission_control, 'mars') and hasattr(self.mission_control.mars, 'plateau'): if hasattr(self.mission_control, 'mars') and hasattr(self.mission_control.mars, 'plateau'):
plateau = self.mission_control.mars.plateau plateau = self.mission_control.mars.plateau
if hasattr(plateau, 'get_ascii_map'): if hasattr(plateau, 'get_ascii_map'):
ascii_map = plateau.get_ascii_map(map_width, map_height) try:
map_lines = ascii_map.split('\n') ascii_map = plateau.get_ascii_map(map_width, map_height)
map_lines = ascii_map.split('\n')
for i, line in enumerate(map_lines):
if current_line + i < height - 3: for i, line in enumerate(map_lines):
self.draw_map_line(current_line + i, line) if current_line + i < height - 3:
self.draw_map_line(current_line + i, line)
current_line += len(map_lines)
else: current_line += len(map_lines)
# Fallback: Einfache Karte map_drawn = True
self.draw_simple_map(current_line, map_width, map_height, rover_info['position']) except:
current_line += map_height pass
else:
# Fallback: Einfache Karte # 2. Versuche direkte Map
if not map_drawn and hasattr(self.mission_control, 'map'):
map_obj = self.mission_control.map
if hasattr(map_obj, 'get_ascii_map'):
try:
ascii_map = map_obj.get_ascii_map(map_width, map_height)
map_lines = ascii_map.split('\n')
for i, line in enumerate(map_lines):
if current_line + i < height - 3:
self.draw_map_line(current_line + i, line)
current_line += len(map_lines)
map_drawn = True
except:
pass
# 3. Fallback: Einfache Karte
if not map_drawn:
self.draw_simple_map(current_line, map_width, map_height, rover_info['position']) self.draw_simple_map(current_line, map_width, map_height, rover_info['position'])
current_line += map_height current_line += map_height
...@@ -217,22 +272,26 @@ class TerminalUI: ...@@ -217,22 +272,26 @@ class TerminalUI:
# Sende Befehl an den Rover # Sende Befehl an den Rover
result = self.mission_control.send_commands(key) result = self.mission_control.send_commands(key)
self.last_command = key self.last_command = key
self.status_message = f"Befehl '{key}' ausgeführt: {result}"
# Verkürze die Ausgabe für bessere Darstellung
if isinstance(result, str) and len(result) > 50:
result_short = result[:47] + "..."
else:
result_short = str(result)
self.status_message = f"Befehl '{key}'{result_short}"
# Aktualisiere Rover-Richtung basierend auf Befehl # Aktualisiere Rover-Richtung basierend auf Befehl
if key == 'L': rover_info = self.get_rover_info()
directions = ['N', 'W', 'S', 'E'] self.rover_direction = rover_info['direction']
current_idx = directions.index(self.rover_direction)
self.rover_direction = directions[(current_idx + 1) % 4]
elif key == 'R':
directions = ['N', 'E', 'S', 'W']
current_idx = directions.index(self.rover_direction)
self.rover_direction = directions[(current_idx + 1) % 4]
self.update_map() self.update_map()
except Exception as e: except Exception as e:
self.status_message = f"Fehler bei Befehl '{key}': {str(e)}" error_msg = str(e)
if len(error_msg) > 40:
error_msg = error_msg[:37] + "..."
self.status_message = f"Fehler bei '{key}': {error_msg}"
else: else:
self.status_message = f"Unbekannter Befehl: {key}" self.status_message = f"Unbekannter Befehl: {key}"
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment