diff --git a/.idea/matrixmania@1.iml b/.idea/matrixmania@1.iml
new file mode 100644
index 0000000..d5b548d
--- /dev/null
+++ b/.idea/matrixmania@1.iml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
index e83515e..76a9fee 100644
--- a/.idea/modules.xml
+++ b/.idea/modules.xml
@@ -4,6 +4,8 @@
+
+
\ No newline at end of file
diff --git a/.idea/wuerfel.iml b/.idea/wuerfel.iml
new file mode 100644
index 0000000..9d0445b
--- /dev/null
+++ b/.idea/wuerfel.iml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/aufgabenblatt_3/matrixmania/AGENTS.md b/aufgabenblatt_3/matrixmania/AGENTS.md
new file mode 100644
index 0000000..febfd69
--- /dev/null
+++ b/aufgabenblatt_3/matrixmania/AGENTS.md
@@ -0,0 +1,10 @@
+# Regeln für dieses Projekt
+
+- Code nach PEP 8, Zeilenlänge maximal 88 Zeichen.
+- Jede Funktion und Methode hat einen Docstring und Type Hints.
+- Vor jedem Commit: `ruff check` und `ruff format`.
+
+## Projektstruktur
+- Quellcode liegt unter "src/matrixmania/", Tests unter "test/test_matrixmania/"
+- Testpakete, Testdateien und Testfunktionen beginnen mit "test_"
+- Tests sind nach Arrange, Act, Assert gegliedert
diff --git a/aufgabenblatt_3/matrixmania/install_dependencies.py b/aufgabenblatt_3/matrixmania/install_dependencies.py
new file mode 100644
index 0000000..5a20e39
--- /dev/null
+++ b/aufgabenblatt_3/matrixmania/install_dependencies.py
@@ -0,0 +1,146 @@
+#!/usr/bin/env python3
+"""Installiert die Abhängigkeiten aus pyproject.toml in die aktuelle Python-Umgebung.
+
+Ersatz für "Install requirements" aus PyCharm, wenn das Projekt eine pyproject.toml
+statt einer requirements.txt hat. Kein Build, keine besondere Projektstruktur nötig,
+nur Standardbibliothek (Python >= 3.11).
+
+Benutzung:
+ In PyCharm: Rechtsklick auf diese Datei -> Run 'install_dependencies'
+ Im Terminal (venv aktiv): python install_dependencies.py
+
+Ohne Parameter wird ALLES installiert:
+ [project].dependencies + alle [project.optional-dependencies] + alle [dependency-groups]
+
+Abweichendes Verhalten:
+ python install_dependencies.py --extra dev nur Basis + Extra "dev"
+ python install_dependencies.py --group test nur Basis + Gruppe "test"
+ python install_dependencies.py --no-main --group dev
+ python install_dependencies.py --list nur anzeigen, nichts installieren
+ python install_dependencies.py --write requirements.txt schreiben statt installieren
+ python install_dependencies.py --write -o reqs.txt
+"""
+from __future__ import annotations
+
+import sys
+
+if sys.version_info < (3, 11):
+ sys.exit("Dieses Skript braucht Python 3.11 oder neuer (tomllib). "
+ f"Aktuell: {sys.version.split()[0]}")
+
+import argparse
+import subprocess
+import tempfile
+import tomllib
+from pathlib import Path
+
+PROJECT_DIR = Path(__file__).resolve().parent
+
+
+def resolve_group(groups: dict, name: str, seen: set[str] | None = None) -> list[str]:
+ """Löst eine Dependency-Group inkl. {include-group = "..."} rekursiv auf."""
+ seen = set() if seen is None else seen
+ if name in seen:
+ raise ValueError(f"Zyklische include-group: {name}")
+ if name not in groups:
+ raise KeyError(f"Dependency-Group '{name}' nicht gefunden")
+ seen.add(name)
+ result: list[str] = []
+ for entry in groups[name]:
+ if isinstance(entry, str):
+ result.append(entry)
+ elif isinstance(entry, dict) and "include-group" in entry:
+ result.extend(resolve_group(groups, entry["include-group"], seen))
+ return result
+
+
+def collect(data: dict, extras: list[str], groups: list[str], no_main: bool) -> list[str]:
+ project = data.get("project", {})
+ optional = project.get("optional-dependencies", {})
+ dep_groups = data.get("dependency-groups", {})
+ deps: list[str] = []
+
+ if not no_main:
+ deps.extend(project.get("dependencies", []))
+ for extra in extras:
+ if extra not in optional:
+ raise KeyError(f"Optional-Dependency '{extra}' nicht gefunden")
+ deps.extend(optional[extra])
+ for group in groups:
+ deps.extend(resolve_group(dep_groups, group))
+
+ # Duplikate entfernen, Reihenfolge behalten
+ return list(dict.fromkeys(d.strip() for d in deps if d.strip()))
+
+
+def main() -> int:
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("-p", "--pyproject", type=Path, default=PROJECT_DIR / "pyproject.toml",
+ help="Pfad zur pyproject.toml (Standard: neben diesem Skript)")
+ p.add_argument("--extra", action="append", default=None,
+ help="nur diese optional-dependencies (mehrfach möglich)")
+ p.add_argument("--group", action="append", default=None,
+ help="nur diese dependency-groups (mehrfach möglich)")
+ p.add_argument("--no-main", action="store_true", help="[project].dependencies weglassen")
+ p.add_argument("--list", action="store_true", help="Abhängigkeiten nur anzeigen")
+ p.add_argument("--write", action="store_true", help="requirements-Datei schreiben statt installieren")
+ p.add_argument("-o", "--output", type=Path, default=PROJECT_DIR / "requirements.txt",
+ help="Zieldatei für --write")
+ args = p.parse_args()
+
+ if not args.pyproject.exists():
+ print(f"{args.pyproject} nicht gefunden", file=sys.stderr)
+ return 1
+ data = tomllib.loads(args.pyproject.read_text(encoding="utf-8"))
+ all_extras = list(data.get("project", {}).get("optional-dependencies", {}))
+ all_groups = list(data.get("dependency-groups", {}))
+
+ # Ohne --extra/--group: alles. Mit einem davon: nur das Gewählte.
+ selective = args.extra is not None or args.group is not None
+ extras = (args.extra or []) if selective else all_extras
+ groups = (args.group or []) if selective else all_groups
+
+ try:
+ deps = collect(data, extras, groups, args.no_main)
+ except (KeyError, ValueError) as e:
+ print(f"Fehler: {e.args[0]}", file=sys.stderr)
+ print(f" Vorhandene --extra: {', '.join(all_extras) or '(keine)'}", file=sys.stderr)
+ print(f" Vorhandene --group: {', '.join(all_groups) or '(keine)'}", file=sys.stderr)
+ return 1
+
+ parts = ([] if args.no_main else ["Basis"]) + [f"extra:{e}" for e in extras] + [f"group:{g}" for g in groups]
+ print(f"Auswahl: {', '.join(parts) or '(nichts)'}")
+
+ if args.list:
+ print("\n".join(deps) or "(keine Abhängigkeiten)")
+ return 0
+
+ content = f"# Automatisch erzeugt aus {args.pyproject.name} – nicht von Hand bearbeiten\n" + "\n".join(deps) + "\n"
+
+ if args.write:
+ args.output.write_text(content, encoding="utf-8")
+ print(f"{len(deps)} Abhängigkeiten -> {args.output}")
+ return 0
+
+ if not deps:
+ print("Keine Abhängigkeiten gefunden – nichts zu tun.")
+ return 0
+
+ if sys.prefix == sys.base_prefix:
+ print("WARNUNG: Es ist kein virtuelles Environment aktiv – es wird in die globale "
+ f"Python-Installation installiert:\n {sys.prefix}", file=sys.stderr)
+ if sys.stdin.isatty() and input("Trotzdem fortfahren? [j/N] ").strip().lower() not in ("j", "ja", "y", "yes"):
+ return 1
+
+ with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, encoding="utf-8") as tmp:
+ tmp.write(content)
+ tmp_path = Path(tmp.name)
+ try:
+ print(f"Installiere {len(deps)} Abhängigkeiten in {sys.prefix}\n")
+ return subprocess.call([sys.executable, "-m", "pip", "install", "-r", str(tmp_path)])
+ finally:
+ tmp_path.unlink(missing_ok=True)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/aufgabenblatt_3/matrixmania/pyproject.toml b/aufgabenblatt_3/matrixmania/pyproject.toml
new file mode 100644
index 0000000..b67cbe7
--- /dev/null
+++ b/aufgabenblatt_3/matrixmania/pyproject.toml
@@ -0,0 +1,10 @@
+[project]
+name = "matrixmania"
+version = "0.1.0"
+dependencies = ["tabulate"]
+
+[project.optional-dependencies]
+dev = ["pytest", "ruff", "pytest-cov"]
+
+[tool.pytest.ini_options]
+pythonpath = "src"
diff --git a/aufgabenblatt_3/matrixmania/src/matrixmania/__init__.py b/aufgabenblatt_3/matrixmania/src/matrixmania/__init__.py
new file mode 100644
index 0000000..b37b058
--- /dev/null
+++ b/aufgabenblatt_3/matrixmania/src/matrixmania/__init__.py
@@ -0,0 +1,19 @@
+"""Paket MatrixMania: Matrixfunktionen für Rotation und Projektion."""
+
+from .compute import (
+ matmul,
+ project_ortho,
+ project_perspective,
+ rot_2D,
+ rot_3D,
+ transpose,
+)
+
+__all__ = [
+ "matmul",
+ "project_ortho",
+ "project_perspective",
+ "rot_2D",
+ "rot_3D",
+ "transpose",
+]
diff --git a/aufgabenblatt_3/matrixmania/src/matrixmania/compute.py b/aufgabenblatt_3/matrixmania/src/matrixmania/compute.py
new file mode 100644
index 0000000..64ec553
--- /dev/null
+++ b/aufgabenblatt_3/matrixmania/src/matrixmania/compute.py
@@ -0,0 +1,174 @@
+"""Funktionen zur linearen Algebra auf Matrizen als verschachtelte Listen."""
+
+import math
+
+from tabulate import tabulate
+
+
+def matmul(
+ matrix_a: list[list[float]], matrix_b: list[list[float]]
+) -> list[list[float]]:
+ """
+ Multipliziert zwei Matrizen miteinander (A * B).
+
+ :param matrix_a: Linke Matrix mit m Zeilen und n Spalten
+ :param matrix_b: Rechte Matrix mit n Zeilen und p Spalten
+ :return: Ergebnismatrix mit m Zeilen und p Spalten
+ :raises ValueError: Wenn die Spaltenzahl von A nicht der Zeilenzahl von B entspricht
+ """
+ if len(matrix_a[0]) != len(matrix_b):
+ raise ValueError("Spaltenzahl von A muss der Zeilenzahl von B entsprechen.")
+
+ result = []
+ for row in matrix_a:
+ new_row = []
+ for col_index in range(len(matrix_b[0])):
+ value = 0
+ for k in range(len(row)):
+ value += row[k] * matrix_b[k][col_index]
+ new_row.append(value)
+ result.append(new_row)
+ return result
+
+
+def transpose(matrix: list[list[float]]) -> list[list[float]]:
+ """
+ Transponiert eine Matrix: Zeilen werden zu Spalten und Spalten zu Zeilen.
+
+ :param matrix: Matrix mit m Zeilen und n Spalten
+ :return: Transponierte Matrix mit n Zeilen und m Spalten
+ :raises ValueError: Bei leerer Matrix oder unterschiedlich langen Zeilen
+ """
+ if not matrix or not matrix[0]:
+ raise ValueError("Die Matrix darf nicht leer sein.")
+
+ column_count = len(matrix[0])
+ for row in matrix:
+ if len(row) != column_count:
+ raise ValueError("Alle Zeilen müssen gleich viele Spalten haben.")
+
+ result = []
+ for col_index in range(column_count):
+ new_row = []
+ for row in matrix:
+ new_row.append(row[col_index])
+ result.append(new_row)
+ return result
+
+
+def rot_2D(angle: float) -> list[list[float]]:
+ """
+ Liefert die 2D-Rotationsmatrix für eine Drehung um den Ursprung.
+
+ :param angle: Drehwinkel im Bogenmaß (gegen den Uhrzeigersinn)
+ :return: 2x2-Rotationsmatrix [[cos, -sin], [sin, cos]]
+ """
+ return [
+ [math.cos(angle), -math.sin(angle)],
+ [math.sin(angle), math.cos(angle)],
+ ]
+
+
+def rot_3D(angle: float, axis: str) -> list[list[float]]:
+ """
+ Liefert die 3D-Rotationsmatrix für eine Drehung um eine Koordinatenachse.
+
+ Formeln (θ = angle):
+
+ - x-Achse: [[1, 0, 0], [0, cos θ, -sin θ], [0, sin θ, cos θ]]
+ - y-Achse: [[cos θ, 0, sin θ], [0, 1, 0], [-sin θ, 0, cos θ]]
+ - z-Achse: [[cos θ, -sin θ, 0], [sin θ, cos θ, 0], [0, 0, 1]]
+
+ :param angle: Drehwinkel im Bogenmaß
+ :param axis: Drehachse, "x", "y" oder "z"
+ :return: 3x3-Rotationsmatrix
+ :raises ValueError: Wenn axis nicht "x", "y" oder "z" ist
+ """
+ cos = math.cos(angle)
+ sin = math.sin(angle)
+ if axis == "x":
+ return [[1, 0, 0], [0, cos, -sin], [0, sin, cos]]
+ if axis == "y":
+ return [[cos, 0, sin], [0, 1, 0], [-sin, 0, cos]]
+ if axis == "z":
+ return [[cos, -sin, 0], [sin, cos, 0], [0, 0, 1]]
+ raise ValueError(f"Ungültige Achse '{axis}', erlaubt sind 'x', 'y' und 'z'.")
+
+
+def project_ortho(
+ point: tuple[float, float, float], scale: float = 1
+) -> tuple[float, float]:
+ """
+ Projiziert einen 3D-Punkt orthogonal auf die xy-Ebene.
+
+ Die z-Koordinate wird ignoriert, x und y werden mit scale multipliziert.
+
+ :param point: 3D-Punkt (x, y, z)
+ :param scale: Skalierungsfaktor für das Ergebnis
+ :return: 2D-Punkt (x * scale, y * scale)
+ """
+ x, y, _ = point
+ return (x * scale, y * scale)
+
+
+def project_perspective(
+ point: tuple[float, float, float],
+ focal_length: float = 1.0,
+ scale: float = 1.0,
+ camera_distance: float = 4.0,
+) -> tuple[float, float]:
+ """
+ Projiziert einen 3D-Punkt perspektivisch auf die Bildschirmebene.
+
+ Formel: x' = x * focal_length / (z + camera_distance) * scale,
+ y' entsprechend.
+
+ :param point: 3D-Punkt (x, y, z)
+ :param focal_length: Brennweite, steuert die Stärke der Perspektive
+ :param scale: Skalierungsfaktor für das Ergebnis
+ :param camera_distance: Abstand der Kamera zum Ursprung
+ :return: 2D-Punkt (x', y')
+ :raises ValueError: Wenn der Punkt auf Höhe oder hinter der Kamera liegt
+ """
+ x, y, z = point
+ depth = z + camera_distance
+ if depth <= 0:
+ raise ValueError("Der Punkt liegt auf Höhe oder hinter der Kamera.")
+ factor = focal_length / depth * scale
+ return (x * factor, y * factor)
+
+
+if __name__ == "__main__":
+ # Test matmul (Beispiel aus dem Skript)
+ matrix_a = [[3, 4, -1, 4], [-2, 2, 5, 1]]
+ matrix_b = [[1, 3, -2], [2, 5, 1], [-1, 4, -4], [2, 3, 6]]
+ matrix_c = matmul(matrix_a, matrix_b)
+ print("Ergebnis C = A * B:")
+ for row in matrix_c:
+ print(row)
+
+ # Zweites Beispiel matmul: Einheitsmatrix ändert nichts
+ identity = [[1, 0], [0, 1]]
+ print("\nEinheitsmatrix * [[5, 6], [7, 8]]:")
+ print(matmul(identity, [[5, 6], [7, 8]])) # Erwartet: [[5, 6], [7, 8]]
+
+ # Fehlerfall matmul: Dimensionen passen nicht
+ try:
+ matmul([[1, 2]], [[1, 2]])
+ except ValueError as error:
+ print("ValueError wie erwartet:", error)
+
+ # Test transpose
+ matrix = [[1, 2, 3], [4, 5, 6]]
+ print("\nTransponiert:")
+ print(transpose(matrix)) # Erwartet: [[1, 4], [2, 5], [3, 6]]
+
+ # Test rot_2D: Punkt (1, 0) um 90 Grad drehen -> erwartet (0, 1)
+ point = transpose([[1, 0]]) # [x, y] wird zur Spalte [[x], [y]]
+ rotated = matmul(rot_2D(math.pi / 2), point)
+ print("\nPunkt (1, 0) um 90 Grad gedreht:")
+ print(round(rotated[0][0], 10), round(rotated[1][0], 10)) # Erwartet: 0.0 1.0
+
+ # Requirements: Matrix mit tabulate ausgeben
+ print("\nRotationsmatrix für 1.0 als Tabelle:")
+ print(tabulate(rot_2D(1.0)))
diff --git a/aufgabenblatt_3/matrixmania/test/test_matrixmania/test_projection.py b/aufgabenblatt_3/matrixmania/test/test_matrixmania/test_projection.py
new file mode 100644
index 0000000..31fffd6
--- /dev/null
+++ b/aufgabenblatt_3/matrixmania/test/test_matrixmania/test_projection.py
@@ -0,0 +1,60 @@
+"""Tests für project_ortho und project_perspective."""
+
+import pytest
+
+from matrixmania import project_ortho, project_perspective
+
+
+def test_project_ortho_without_scale():
+ # Arrange
+ point = (1.0, 2.0, 3.0)
+ # Act
+ result = project_ortho(point)
+ # Assert
+ assert result == (1.0, 2.0)
+
+
+def test_project_ortho_with_scale_100():
+ # Arrange
+ point = (1.0, 2.0, 3.0)
+ # Act
+ result = project_ortho(point, scale=100)
+ # Assert
+ assert result == pytest.approx((100.0, 200.0))
+
+
+def test_project_perspective_without_scale():
+ # Arrange
+ point = (1.0, 2.0, 3.0)
+ # Act
+ result = project_perspective(point, focal_length=1, scale=1)
+ # Assert
+ assert result == pytest.approx((1 / 7, 2 / 7))
+
+
+def test_project_perspective_with_scale_100_and_focal_length_2():
+ # Arrange
+ point = (1.0, 2.0, 3.0)
+ # Act
+ result = project_perspective(point, focal_length=2, scale=100)
+ # Assert
+ assert result == pytest.approx((200 / 7, 400 / 7))
+
+
+def test_project_perspective_far_point_appears_smaller():
+ # Arrange
+ near = (1.0, 1.0, 0.0)
+ far = (1.0, 1.0, 10.0)
+ # Act
+ near_x, _ = project_perspective(near)
+ far_x, _ = project_perspective(far)
+ # Assert
+ assert far_x < near_x
+
+
+def test_project_perspective_point_behind_camera_raises():
+ # Arrange
+ point = (1.0, 1.0, -4.0)
+ # Act & Assert
+ with pytest.raises(ValueError):
+ project_perspective(point)
diff --git a/aufgabenblatt_3/matrixmania/test/test_matrixmania/test_rot.py b/aufgabenblatt_3/matrixmania/test/test_matrixmania/test_rot.py
new file mode 100644
index 0000000..47e6acc
--- /dev/null
+++ b/aufgabenblatt_3/matrixmania/test/test_matrixmania/test_rot.py
@@ -0,0 +1,65 @@
+"""Tests für rot_2D und rot_3D."""
+
+import math
+
+import pytest
+
+from matrixmania import matmul, rot_2D, rot_3D, transpose
+
+
+def rotate(matrix: list[list[float]], point: list[float]) -> list[float]:
+ """Dreht einen Punkt mit einer Rotationsmatrix und gibt ihn als Liste zurück."""
+ result = matmul(matrix, transpose([point]))
+ return [row[0] for row in result]
+
+
+def test_rot_2D_90_degrees():
+ # Arrange
+ point = [1, 0]
+ # Act
+ rotated = rotate(rot_2D(math.pi / 2), point)
+ # Assert
+ assert rotated == pytest.approx([0, 1])
+
+
+def test_rot_2D_zero_angle_is_identity():
+ # Arrange
+ angle = 0
+ # Act
+ matrix = rot_2D(angle)
+ # Assert
+ assert matrix == [[1, 0], [0, 1]]
+
+
+@pytest.mark.parametrize(
+ "axis, point, expected",
+ [
+ ("x", [0, 1, 0], [0, 0, 1]),
+ ("y", [0, 0, 1], [1, 0, 0]),
+ ("z", [1, 0, 0], [0, 1, 0]),
+ ],
+)
+def test_rot_3D_90_degrees(axis, point, expected):
+ # Arrange
+ angle = math.pi / 2
+ # Act
+ rotated = rotate(rot_3D(angle, axis), point)
+ # Assert
+ assert rotated == pytest.approx(expected)
+
+
+def test_rot_3D_point_on_axis_stays():
+ # Arrange
+ point = [1, 0, 0]
+ # Act
+ rotated = rotate(rot_3D(1.23, "x"), point)
+ # Assert
+ assert rotated == pytest.approx(point)
+
+
+def test_rot_3D_invalid_axis_raises():
+ # Arrange
+ axis = "w"
+ # Act & Assert
+ with pytest.raises(ValueError):
+ rot_3D(1.0, axis)
diff --git a/aufgabenblatt_3/wuerfel/install_dependencies.py b/aufgabenblatt_3/wuerfel/install_dependencies.py
new file mode 100644
index 0000000..5a20e39
--- /dev/null
+++ b/aufgabenblatt_3/wuerfel/install_dependencies.py
@@ -0,0 +1,146 @@
+#!/usr/bin/env python3
+"""Installiert die Abhängigkeiten aus pyproject.toml in die aktuelle Python-Umgebung.
+
+Ersatz für "Install requirements" aus PyCharm, wenn das Projekt eine pyproject.toml
+statt einer requirements.txt hat. Kein Build, keine besondere Projektstruktur nötig,
+nur Standardbibliothek (Python >= 3.11).
+
+Benutzung:
+ In PyCharm: Rechtsklick auf diese Datei -> Run 'install_dependencies'
+ Im Terminal (venv aktiv): python install_dependencies.py
+
+Ohne Parameter wird ALLES installiert:
+ [project].dependencies + alle [project.optional-dependencies] + alle [dependency-groups]
+
+Abweichendes Verhalten:
+ python install_dependencies.py --extra dev nur Basis + Extra "dev"
+ python install_dependencies.py --group test nur Basis + Gruppe "test"
+ python install_dependencies.py --no-main --group dev
+ python install_dependencies.py --list nur anzeigen, nichts installieren
+ python install_dependencies.py --write requirements.txt schreiben statt installieren
+ python install_dependencies.py --write -o reqs.txt
+"""
+from __future__ import annotations
+
+import sys
+
+if sys.version_info < (3, 11):
+ sys.exit("Dieses Skript braucht Python 3.11 oder neuer (tomllib). "
+ f"Aktuell: {sys.version.split()[0]}")
+
+import argparse
+import subprocess
+import tempfile
+import tomllib
+from pathlib import Path
+
+PROJECT_DIR = Path(__file__).resolve().parent
+
+
+def resolve_group(groups: dict, name: str, seen: set[str] | None = None) -> list[str]:
+ """Löst eine Dependency-Group inkl. {include-group = "..."} rekursiv auf."""
+ seen = set() if seen is None else seen
+ if name in seen:
+ raise ValueError(f"Zyklische include-group: {name}")
+ if name not in groups:
+ raise KeyError(f"Dependency-Group '{name}' nicht gefunden")
+ seen.add(name)
+ result: list[str] = []
+ for entry in groups[name]:
+ if isinstance(entry, str):
+ result.append(entry)
+ elif isinstance(entry, dict) and "include-group" in entry:
+ result.extend(resolve_group(groups, entry["include-group"], seen))
+ return result
+
+
+def collect(data: dict, extras: list[str], groups: list[str], no_main: bool) -> list[str]:
+ project = data.get("project", {})
+ optional = project.get("optional-dependencies", {})
+ dep_groups = data.get("dependency-groups", {})
+ deps: list[str] = []
+
+ if not no_main:
+ deps.extend(project.get("dependencies", []))
+ for extra in extras:
+ if extra not in optional:
+ raise KeyError(f"Optional-Dependency '{extra}' nicht gefunden")
+ deps.extend(optional[extra])
+ for group in groups:
+ deps.extend(resolve_group(dep_groups, group))
+
+ # Duplikate entfernen, Reihenfolge behalten
+ return list(dict.fromkeys(d.strip() for d in deps if d.strip()))
+
+
+def main() -> int:
+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ p.add_argument("-p", "--pyproject", type=Path, default=PROJECT_DIR / "pyproject.toml",
+ help="Pfad zur pyproject.toml (Standard: neben diesem Skript)")
+ p.add_argument("--extra", action="append", default=None,
+ help="nur diese optional-dependencies (mehrfach möglich)")
+ p.add_argument("--group", action="append", default=None,
+ help="nur diese dependency-groups (mehrfach möglich)")
+ p.add_argument("--no-main", action="store_true", help="[project].dependencies weglassen")
+ p.add_argument("--list", action="store_true", help="Abhängigkeiten nur anzeigen")
+ p.add_argument("--write", action="store_true", help="requirements-Datei schreiben statt installieren")
+ p.add_argument("-o", "--output", type=Path, default=PROJECT_DIR / "requirements.txt",
+ help="Zieldatei für --write")
+ args = p.parse_args()
+
+ if not args.pyproject.exists():
+ print(f"{args.pyproject} nicht gefunden", file=sys.stderr)
+ return 1
+ data = tomllib.loads(args.pyproject.read_text(encoding="utf-8"))
+ all_extras = list(data.get("project", {}).get("optional-dependencies", {}))
+ all_groups = list(data.get("dependency-groups", {}))
+
+ # Ohne --extra/--group: alles. Mit einem davon: nur das Gewählte.
+ selective = args.extra is not None or args.group is not None
+ extras = (args.extra or []) if selective else all_extras
+ groups = (args.group or []) if selective else all_groups
+
+ try:
+ deps = collect(data, extras, groups, args.no_main)
+ except (KeyError, ValueError) as e:
+ print(f"Fehler: {e.args[0]}", file=sys.stderr)
+ print(f" Vorhandene --extra: {', '.join(all_extras) or '(keine)'}", file=sys.stderr)
+ print(f" Vorhandene --group: {', '.join(all_groups) or '(keine)'}", file=sys.stderr)
+ return 1
+
+ parts = ([] if args.no_main else ["Basis"]) + [f"extra:{e}" for e in extras] + [f"group:{g}" for g in groups]
+ print(f"Auswahl: {', '.join(parts) or '(nichts)'}")
+
+ if args.list:
+ print("\n".join(deps) or "(keine Abhängigkeiten)")
+ return 0
+
+ content = f"# Automatisch erzeugt aus {args.pyproject.name} – nicht von Hand bearbeiten\n" + "\n".join(deps) + "\n"
+
+ if args.write:
+ args.output.write_text(content, encoding="utf-8")
+ print(f"{len(deps)} Abhängigkeiten -> {args.output}")
+ return 0
+
+ if not deps:
+ print("Keine Abhängigkeiten gefunden – nichts zu tun.")
+ return 0
+
+ if sys.prefix == sys.base_prefix:
+ print("WARNUNG: Es ist kein virtuelles Environment aktiv – es wird in die globale "
+ f"Python-Installation installiert:\n {sys.prefix}", file=sys.stderr)
+ if sys.stdin.isatty() and input("Trotzdem fortfahren? [j/N] ").strip().lower() not in ("j", "ja", "y", "yes"):
+ return 1
+
+ with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, encoding="utf-8") as tmp:
+ tmp.write(content)
+ tmp_path = Path(tmp.name)
+ try:
+ print(f"Installiere {len(deps)} Abhängigkeiten in {sys.prefix}\n")
+ return subprocess.call([sys.executable, "-m", "pip", "install", "-r", str(tmp_path)])
+ finally:
+ tmp_path.unlink(missing_ok=True)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/aufgabenblatt_3/wuerfel/main.py b/aufgabenblatt_3/wuerfel/main.py
new file mode 100644
index 0000000..ec2a3c1
--- /dev/null
+++ b/aufgabenblatt_3/wuerfel/main.py
@@ -0,0 +1,7 @@
+"""Startskript für den rotierenden Würfel."""
+
+from spiel.cube_game import CubeGame
+
+if __name__ == "__main__":
+ cube_game = CubeGame()
+ cube_game.run()
diff --git a/aufgabenblatt_3/wuerfel/pyproject.toml b/aufgabenblatt_3/wuerfel/pyproject.toml
new file mode 100644
index 0000000..941120c
--- /dev/null
+++ b/aufgabenblatt_3/wuerfel/pyproject.toml
@@ -0,0 +1,4 @@
+[project]
+name = "wuerfel"
+version = "0.1.0"
+dependencies = ["pygame-ce"]
diff --git a/aufgabenblatt_3/wuerfel/spiel/__init__.py b/aufgabenblatt_3/wuerfel/spiel/__init__.py
new file mode 100644
index 0000000..b996f9b
--- /dev/null
+++ b/aufgabenblatt_3/wuerfel/spiel/__init__.py
@@ -0,0 +1 @@
+"""Paket spiel: Basisklasse, Matrixfunktionen und der rotierende Würfel."""
diff --git a/aufgabenblatt_3/wuerfel/spiel/compute.py b/aufgabenblatt_3/wuerfel/spiel/compute.py
new file mode 100644
index 0000000..122da16
--- /dev/null
+++ b/aufgabenblatt_3/wuerfel/spiel/compute.py
@@ -0,0 +1,136 @@
+"""Funktionen zur linearen Algebra auf Matrizen als verschachtelte Listen."""
+
+import math
+
+
+def matmul(
+ matrix_a: list[list[float]], matrix_b: list[list[float]]
+) -> list[list[float]]:
+ """
+ Multipliziert zwei Matrizen miteinander (A * B).
+
+ :param matrix_a: Linke Matrix mit m Zeilen und n Spalten
+ :param matrix_b: Rechte Matrix mit n Zeilen und p Spalten
+ :return: Ergebnismatrix mit m Zeilen und p Spalten
+ :raises ValueError: Wenn die Spaltenzahl von A nicht der Zeilenzahl von B entspricht
+ """
+ if len(matrix_a[0]) != len(matrix_b):
+ raise ValueError("Spaltenzahl von A muss der Zeilenzahl von B entsprechen.")
+
+ result = []
+ for row in matrix_a:
+ new_row = []
+ for col_index in range(len(matrix_b[0])):
+ value = 0
+ for k in range(len(row)):
+ value += row[k] * matrix_b[k][col_index]
+ new_row.append(value)
+ result.append(new_row)
+ return result
+
+
+def transpose(matrix: list[list[float]]) -> list[list[float]]:
+ """
+ Transponiert eine Matrix: Zeilen werden zu Spalten und Spalten zu Zeilen.
+
+ :param matrix: Matrix mit m Zeilen und n Spalten
+ :return: Transponierte Matrix mit n Zeilen und m Spalten
+ :raises ValueError: Bei leerer Matrix oder unterschiedlich langen Zeilen
+ """
+ if not matrix or not matrix[0]:
+ raise ValueError("Die Matrix darf nicht leer sein.")
+
+ column_count = len(matrix[0])
+ for row in matrix:
+ if len(row) != column_count:
+ raise ValueError("Alle Zeilen müssen gleich viele Spalten haben.")
+
+ result = []
+ for col_index in range(column_count):
+ new_row = []
+ for row in matrix:
+ new_row.append(row[col_index])
+ result.append(new_row)
+ return result
+
+
+def rot_2D(angle: float) -> list[list[float]]:
+ """
+ Liefert die 2D-Rotationsmatrix für eine Drehung um den Ursprung.
+
+ :param angle: Drehwinkel im Bogenmaß (gegen den Uhrzeigersinn)
+ :return: 2x2-Rotationsmatrix [[cos, -sin], [sin, cos]]
+ """
+ return [
+ [math.cos(angle), -math.sin(angle)],
+ [math.sin(angle), math.cos(angle)],
+ ]
+
+
+def rot_3D(angle: float, axis: str) -> list[list[float]]:
+ """
+ Liefert die 3D-Rotationsmatrix für eine Drehung um eine Koordinatenachse.
+
+ Formeln (θ = angle):
+
+ - x-Achse: [[1, 0, 0], [0, cos θ, -sin θ], [0, sin θ, cos θ]]
+ - y-Achse: [[cos θ, 0, sin θ], [0, 1, 0], [-sin θ, 0, cos θ]]
+ - z-Achse: [[cos θ, -sin θ, 0], [sin θ, cos θ, 0], [0, 0, 1]]
+
+ :param angle: Drehwinkel im Bogenmaß
+ :param axis: Drehachse, "x", "y" oder "z"
+ :return: 3x3-Rotationsmatrix
+ :raises ValueError: Wenn axis nicht "x", "y" oder "z" ist
+ """
+ cos = math.cos(angle)
+ sin = math.sin(angle)
+ if axis == "x":
+ return [[1, 0, 0], [0, cos, -sin], [0, sin, cos]]
+ if axis == "y":
+ return [[cos, 0, sin], [0, 1, 0], [-sin, 0, cos]]
+ if axis == "z":
+ return [[cos, -sin, 0], [sin, cos, 0], [0, 0, 1]]
+ raise ValueError(f"Ungültige Achse '{axis}', erlaubt sind 'x', 'y' und 'z'.")
+
+
+def project_ortho(
+ point: tuple[float, float, float], scale: float = 1
+) -> tuple[float, float]:
+ """
+ Projiziert einen 3D-Punkt orthogonal auf die xy-Ebene.
+
+ Die z-Koordinate wird ignoriert, x und y werden mit scale multipliziert.
+
+ :param point: 3D-Punkt (x, y, z)
+ :param scale: Skalierungsfaktor für das Ergebnis
+ :return: 2D-Punkt (x * scale, y * scale)
+ """
+ x, y, _ = point
+ return (x * scale, y * scale)
+
+
+def project_perspective(
+ point: tuple[float, float, float],
+ focal_length: float = 1.0,
+ scale: float = 1.0,
+ camera_distance: float = 4.0,
+) -> tuple[float, float]:
+ """
+ Projiziert einen 3D-Punkt perspektivisch auf die Bildschirmebene.
+
+ Formel: x' = x * focal_length / (z + camera_distance) * scale,
+ y' entsprechend.
+
+ :param point: 3D-Punkt (x, y, z)
+ :param focal_length: Brennweite, steuert die Stärke der Perspektive
+ :param scale: Skalierungsfaktor für das Ergebnis
+ :param camera_distance: Abstand der Kamera zum Ursprung
+ :return: 2D-Punkt (x', y')
+ :raises ValueError: Wenn der Punkt auf Höhe oder hinter der Kamera liegt
+ """
+ x, y, z = point
+ depth = z + camera_distance
+ if depth <= 0:
+ raise ValueError("Der Punkt liegt auf Höhe oder hinter der Kamera.")
+ factor = focal_length / depth * scale
+ return (x * factor, y * factor)
diff --git a/aufgabenblatt_3/wuerfel/spiel/cube_game.py b/aufgabenblatt_3/wuerfel/spiel/cube_game.py
new file mode 100644
index 0000000..6a79779
--- /dev/null
+++ b/aufgabenblatt_3/wuerfel/spiel/cube_game.py
@@ -0,0 +1,115 @@
+"""Ein Würfel, der sich mit den Pfeiltasten drehen lässt."""
+
+import pygame
+
+from .compute import matmul, project_ortho, rot_3D, transpose
+from .game import Game
+
+VERTICES = [
+ (-1, -1, -1),
+ (1, -1, -1),
+ (1, 1, -1),
+ (-1, 1, -1),
+ (-1, -1, 1),
+ (1, -1, 1),
+ (1, 1, 1),
+ (-1, 1, 1),
+]
+SCALE = 100
+ANGLE_STEP = 0.05
+BLACK = (0, 0, 0)
+WHITE = (255, 255, 255)
+
+
+class CubeGame(Game):
+ """Rotierender Würfel: Pfeiltasten drehen um die x- und y-Achse."""
+
+ def __init__(
+ self,
+ title: str = "Rotierender Würfel",
+ fps: int = 60,
+ size: tuple[int, int] = (640, 400),
+ ) -> None:
+ """Legt Startwinkel, Kanten und Bildschirmpunkte des Würfels fest."""
+ super().__init__(title, fps, size)
+ self.angle_x: float = 0
+ self.angle_y: float = 0
+ self.edges: list[tuple[int, int]] = find_edges(VERTICES)
+ self.screen_points: list[tuple[float, float]] = []
+
+ def init_game(self) -> None:
+ """Initialisiert pygame und lässt gedrückte Tasten wiederholen."""
+ super().init_game()
+ pygame.key.set_repeat(30, 30)
+
+ def handle_event(self, event: pygame.event.Event) -> bool:
+ """Ändert die Drehwinkel bei Druck auf die Pfeiltasten."""
+ if event.type == pygame.KEYDOWN:
+ if event.key == pygame.K_UP:
+ self.angle_x -= ANGLE_STEP
+ elif event.key == pygame.K_DOWN:
+ self.angle_x += ANGLE_STEP
+ elif event.key == pygame.K_LEFT:
+ self.angle_y -= ANGLE_STEP
+ elif event.key == pygame.K_RIGHT:
+ self.angle_y += ANGLE_STEP
+ return super().handle_event(event)
+
+ def update_game(self) -> bool:
+ """Berechnet die Bildschirmpositionen aller Eckpunkte neu."""
+ rotation = matmul(rot_3D(self.angle_y, "y"), rot_3D(self.angle_x, "x"))
+ self.screen_points = [
+ self.to_screen(rotate(rotation, vertex)) for vertex in VERTICES
+ ]
+ return True
+
+ def draw_game(self) -> None:
+ """Zeichnet alle Kanten des Würfels."""
+ self.screen.fill(BLACK)
+ for start, end in self.edges:
+ pygame.draw.line(
+ self.screen, WHITE, self.screen_points[start], self.screen_points[end]
+ )
+ pygame.display.flip()
+
+ def to_screen(self, point: tuple[float, float, float]) -> tuple[float, float]:
+ """
+ Projiziert einen 3D-Punkt orthogonal und verschiebt ihn in die Fenstermitte.
+
+ :param point: 3D-Punkt (x, y, z)
+ :return: Punkt in Fensterkoordinaten
+ """
+ x, y = project_ortho(point, scale=SCALE)
+ return (x + self.size[0] / 2, y + self.size[1] / 2)
+
+
+def rotate(
+ rotation: list[list[float]], point: tuple[float, float, float]
+) -> tuple[float, float, float]:
+ """
+ Dreht einen 3D-Punkt mit einer Rotationsmatrix.
+
+ :param rotation: 3x3-Rotationsmatrix
+ :param point: 3D-Punkt (x, y, z)
+ :return: Gedrehter 3D-Punkt
+ """
+ result = matmul(rotation, transpose([list(point)]))
+ return (result[0][0], result[1][0], result[2][0])
+
+
+def find_edges(vertices: list[tuple[int, int, int]]) -> list[tuple[int, int]]:
+ """
+ Findet alle Kanten des Würfels.
+
+ Zwei Ecken sind verbunden, wenn sie sich in genau einer Koordinate unterscheiden.
+
+ :param vertices: Eckpunkte des Würfels
+ :return: Liste von Indexpaaren (Start, Ende)
+ """
+ edges = []
+ for i in range(len(vertices)):
+ for j in range(i + 1, len(vertices)):
+ differences = sum(a != b for a, b in zip(vertices[i], vertices[j]))
+ if differences == 1:
+ edges.append((i, j))
+ return edges
diff --git a/aufgabenblatt_3/wuerfel/spiel/game.py b/aufgabenblatt_3/wuerfel/spiel/game.py
new file mode 100644
index 0000000..e88c245
--- /dev/null
+++ b/aufgabenblatt_3/wuerfel/spiel/game.py
@@ -0,0 +1,98 @@
+"""Basisklasse ``Game`` für einfache pygame-Anwendungen."""
+
+import pygame
+
+
+class Game:
+ """Basisklasse für pygame-Spiele.
+
+ Unterklassen passen das Verhalten durch Überschreiben von
+ :meth:`handle_event`, :meth:`update_game` und :meth:`draw_game` an.
+ """
+
+ def __init__(
+ self,
+ title: str,
+ fps: int = 60,
+ size: tuple[int, int] = (640, 400),
+ ) -> None:
+ """Legt Fenstertitel, Bildrate und Fenstergröße fest.
+
+ Args:
+ title: Titel des Fensters.
+ fps: Maximale Bilder pro Sekunde.
+ size: Fenstergröße als (Breite, Höhe) in Pixeln.
+ """
+ self.title: str = title
+ self.fps: int = fps
+ self.size: tuple[int, int] = size
+ self.clock: pygame.time.Clock = pygame.time.Clock()
+ self.dt: float = 0
+ self.screen: pygame.Surface | None = None
+
+ def init_game(self) -> None:
+ """Initialisiert pygame und erzeugt das Fenster."""
+ pygame.init()
+ pygame.display.set_caption(self.title)
+ self.screen = pygame.display.set_mode(self.size)
+
+ def game_loop(self) -> None:
+ """Führt die Hauptschleife aus, bis Events oder Update ``False`` liefern."""
+ while True:
+ # Berechnung der Zeitdifferenz seit dem letzten Frame
+ self.dt = self.clock.tick(self.fps) / 1000
+ if self.event_handling() == False:
+ break
+ if self.update_game() == False:
+ break
+ self.draw_game()
+
+ def exit_game(self) -> None:
+ """Beendet pygame."""
+ pygame.quit()
+
+ def event_handling(self) -> bool:
+ """Verteilt alle anstehenden Events an :meth:`handle_event`.
+
+ Bleibt in der Unterklasse unverändert.
+
+ Returns:
+ ``False``, sobald ein Event das Spiel beenden soll, sonst ``True``.
+ """
+ for event in pygame.event.get():
+ if not self.handle_event(event):
+ return False
+ return True
+
+ def handle_event(self, event: pygame.event.Event) -> bool:
+ """Verarbeitet ein einzelnes Event.
+
+ Wird in der Unterklasse überschrieben.
+
+ Args:
+ event: Das zu verarbeitende pygame-Event.
+
+ Returns:
+ ``False`` bei ``pygame.QUIT``, sonst ``True``.
+ """
+ if event.type == pygame.QUIT:
+ return False
+ return True
+
+ def update_game(self) -> bool:
+ """Aktualisiert den Spielzustand um einen Frame.
+
+ Returns:
+ ``False``, wenn das Spiel beendet werden soll, sonst ``True``.
+ """
+ return True
+
+ def draw_game(self) -> None:
+ """Zeichnet den aktuellen Frame und bringt ihn zur Anzeige."""
+ pygame.display.flip()
+
+ def run(self) -> None:
+ """Startet das Spiel: Initialisierung, Hauptschleife, Beenden."""
+ self.init_game()
+ self.game_loop()
+ self.exit_game()
\ No newline at end of file
diff --git a/woche 42/08_10.py b/woche 42/08_10.py
new file mode 100644
index 0000000..3a3b670
--- /dev/null
+++ b/woche 42/08_10.py
@@ -0,0 +1,59 @@
+def matmul(a: list[list[float | int]], b: list[list[float | int]]) -> list[list[float | int]]:
+ if not a or not a[0] or not b or not b[0]:
+ raise ValueError("Matrizen dürfen nicht leer sein.")
+
+ rows_a = len(a)
+ cols_a = len(a[0])
+ rows_b = len(b)
+ cols_b = len(b[0])
+
+ # Auf unregelmäßige (jagged) Matrizen prüfen
+ if any(len(row) != cols_a for row in a):
+ raise ValueError("Matrix a enthält Zeilen unterschiedlicher Länge.")
+ if any(len(row) != cols_b for row in b):
+ raise ValueError("Matrix b enthält Zeilen unterschiedlicher Länge.")
+
+ # Dimensionenprüfung für die Multiplikation
+ if cols_a != rows_b:
+ raise ValueError(
+ f"Inkompatible Dimensionen: Spalten von a ({cols_a}) "
+ f"müssen gleich Zeilen von b ({rows_b}) sein."
+ )
+
+ # Ergebnis-Matrix mit Nullen initialisieren (rows_a x cols_b)
+ result = [[0.0 for _ in range(cols_b)] for _ in range(rows_a)]
+
+ for i in range(rows_a):
+ for j in range(cols_b):
+ for k in range(cols_a):
+ result[i][j] += a[i][k] * b[k][j]
+
+ return result
+
+
+if __name__ == "__main__":
+ # Beispiel 1: Erfolgreiche Multiplikation (2x3 mal 3x2)
+ mat1 = [
+ [1, 2, 3],
+ [4, 5, 6]
+ ]
+ mat2 = [
+ [7, 8],
+ [9, 1],
+ [2, 3]
+ ]
+ print("Ergebnis Beispiel 1:")
+ print(matmul(mat1, mat2))
+ # Erwartetes Ergebnis: [[31, 19], [85, 55]]
+
+ # Beispiel 2: Fehlerfall (Dimensionen passen nicht)
+ try:
+ mat3 = [[1, 2]]
+ matmul(mat1, mat3)
+ except ValueError as Error:
+ print(f"Erfolgreich abgefangener Fehler (Beispiel 2): {Error}")
+
+
+"""Docstring und Type Hints sind vorhanden und stimmen mit dem Code überein.
+• Namen sind aussagekräftig.
+• Fehlerfälle werden behandelt, z. B. nicht passende Dimensionen"""
\ No newline at end of file