commit 3cc07d2575e06a46fa4a3d9f082353581825d8d5 Author: Anna Date: Thu Nov 5 01:25:22 2026 +0100 würfel läuft diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..30cf57e --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,10 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# Ignored default folder with query files +/queries/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml new file mode 100644 index 0000000..105ce2d --- /dev/null +++ b/.idea/inspectionProfiles/profiles_settings.xml @@ -0,0 +1,6 @@ + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..85b4c38 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.idea/wuerfel.iml b/.idea/wuerfel.iml new file mode 100644 index 0000000..d3db88b --- /dev/null +++ b/.idea/wuerfel.iml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/install_dependencies.py b/install_dependencies.py new file mode 100644 index 0000000..5a20e39 --- /dev/null +++ b/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/main.py b/main.py new file mode 100644 index 0000000..e1faeb8 --- /dev/null +++ b/main.py @@ -0,0 +1,5 @@ +from spiel.cube_game import CubeGame + +if __name__ == "__main__": + game = CubeGame() + game.run() \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..088d083 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,10 @@ +[project] +name = "wuerfel" +version = "0.1.0" +dependencies = ["pygame"] + +[tool.pytest.ini_options] +pythonpath = "spiel" + +[project.optional-dependencies] +dev = ["pytest", "ruff", "pytest-cov"] \ No newline at end of file diff --git a/spiel/__init__.py b/spiel/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/spiel/compute.py b/spiel/compute.py new file mode 100644 index 0000000..0efdef9 --- /dev/null +++ b/spiel/compute.py @@ -0,0 +1,184 @@ +from __future__ import annotations + +import math +from collections.abc import Sequence + +Matrix = Sequence[Sequence[float]] + + +def matmul(left: Matrix, right: Matrix) -> list[list[float]]: + """Multiply two matrices and return a new matrix. + + Args: + left: Matrix of shape (rows_left, cols_left). + right: Matrix of shape (rows_right, cols_right). + + Returns: + A new matrix of shape (rows_left, cols_right). + + Raises: + ValueError: If either input is empty, ragged, or if + cols_left != rows_right. + """ + # Validate first matrix (rows and columns), raise if invalid. + _validate(left, "left") + # Validate second matrix for similar conditions. + _validate(right, "right") + + # Number of columns in left matrix. + cols_left = len(left[0]) + # Number of rows in right matrix. + rows_right = len(right) + # Ensure the inner dimensions are compatible. + if cols_left != rows_right: + raise ValueError( + f"dimension mismatch: left has {cols_left} columns, " + f"right has {rows_right} rows" + ) + + # Number of columns in right matrix. + cols_right = len(right[0]) + # Prepare result container: rows of left × columns of right. + result: list[list[float]] = [] + # Iterate over rows of left matrix. + for i in range(len(left)): + row: list[float] = [] + # Iterate over columns of right matrix. + for j in range(cols_right): + total = 0.0 + # Accumulate dot product of row i of left and column j of right. + for k in range(cols_left): + total += left[i][k] * right[k][j] + row.append(total) + result.append(row) + return result + +def rot_2D(theta: float) -> list[list[float]]: + """Return the 2‑D rotation matrix for a given angle. + Parameters + theta + Rotation angle in radians. + Returns + list[list[float]] + 2×2 rotation matrix ``[[cosθ, -sinθ], [sinθ, cosθ]]``. + """ + c = math.cos(theta) + s = math.sin(theta) + return [[c, -s], [s, c]] + +def rot_3D(angle: float, axis: str) -> list[list[float]]: + """Return a 3×3 rotation matrix for a rotation around *axis*. + + Parameters + ---------- + angle : float + Rotation angle in radians. + axis : str + Axis of rotation, one of "x", "y" or "z". + + Returns + ------- + list[list[float]] + The 3×3 rotation matrix. + + Raises + ------ + ValueError + If *axis* is not one of "x", "y" or "z". + """ + c = math.cos(angle) + s = math.sin(angle) + if axis == "x": + return [[1, 0, 0], [0, c, -s], [0, s, c]] + if axis == "y": + return [[c, 0, s], [0, 1, 0], [-s, 0, c]] + if axis == "z": + return [[c, -s, 0], [s, c, 0], [0, 0, 1]] + raise ValueError(f"Unsupported rotation axis: {axis}") + +def _validate(matrix: Matrix, name: str) -> None: + """Check that *matrix* is a non‑empty, rectangular 2D sequence. + Validation rules: + * The outer sequence must contain at least one row. + * Every row must have the same number of columns. + * No empty rows are allowed. + Raises: + ValueError: If the matrix is empty, has zero columns, or is ragged. + """ + if len(matrix) == 0: + raise ValueError(f"{name} matrix is empty") + width = len(matrix[0]) + if width == 0: + raise ValueError(f"{name} matrix has no columns") + for index, row in enumerate(matrix): + if len(row) != width: + raise ValueError( + f"{name} matrix is ragged: row 0 has {width} columns, " + f"row {index} has {len(row)}" + ) + +def transpose(matrix: Matrix) -> list[list[float]]: + """Transponieren: Alle Zeilen werden zu Spalten und alle Spalten zu Zeilen. + Parameters + matrix + Matrix in Form ``Sequence[Sequence[float]]``. + Returns + list[list[float]] + Die transponierte Matrix. + Raises + ValueError + Wenn ``matrix`` leer ist oder nicht gleichmäßig viele Spalten + in den Zeilen hat. + """ + _validate(matrix, "matrix") + rows = len(matrix) + cols = len(matrix[0]) + transposed: list[list[float]] = [] + for c in range(cols): + new_row: list[float] = [] + for r in range(rows): + new_row.append(matrix[r][c]) + transposed.append(new_row) + +if __name__ == "__main__": + # Example 1: standard 2x3 * 3x2 multiplication. + a = [ + [1, 2, 3], + [4, 5, 6], + ] + b = [ + [7, 8], + [9, 10], + [11, 12], + ] + expected = [ + [58, 64], + [139, 154], + ] + assert matmul(a, b) == expected, f"example 1 failed: {matmul(a, b)}" + print("example 1 passed:", matmul(a, b)) + + # Example 2: multiplication with the identity matrix changes nothing. + identity = [ + [1, 0, 0], + [0, 1, 0], + [0, 0, 1], + ] + c = [ + [2, -1, 0], + [0, 3, 4], + [5, 6, -2], + ] + assert matmul(c, identity) == c, "example 2 failed" + print("example 2 passed:", matmul(c, identity)) + + # Example 3: mismatched dimensions must raise ValueError. + try: + matmul([[1, 2, 3]], [[1, 2]]) + except ValueError as error: + print("example 3 passed:", error) + + + + + diff --git a/spiel/cube_game.py b/spiel/cube_game.py new file mode 100644 index 0000000..e20706d --- /dev/null +++ b/spiel/cube_game.py @@ -0,0 +1,81 @@ +import pygame +from typing import List, Tuple + +from spiel.game import Game +from spiel.compute import rot_3D, matmul +from spiel.projection import project_ortho + + +class CubeGame(Game): + """A simple 3D cube game demo.""" + + def __init__(self): + super().__init__("3D Cube", 60, (640, 480)) + # cube corners + self.corners: List[Tuple[float, float, float]] = [ + (-1, -1, -1), + (1, -1, -1), + (1, 1, -1), + (-1, 1, -1), + (-1, -1, 1), + (1, -1, 1), + (1, 1, 1), + (-1, 1, 1), + ] + self.angle_x = 0.0 + self.angle_y = 0.0 + # edges between corners that differ in exactly one coordinate + self.edges = [ + (0, 1), + (1, 2), + (2, 3), + (3, 0), + (4, 5), + (5, 6), + (6, 7), + (7, 4), + (0, 4), + (1, 5), + (2, 6), + (3, 7), + ] + self.projected: List[Tuple[float, float]] = [] + + def update_game(self) -> bool: + # tasteneingaben verarbeiten + keys = pygame.key.get_pressed() + if keys[pygame.K_LEFT]: + self.angle_y -= 0.05 + if keys[pygame.K_RIGHT]: + self.angle_y += 0.05 + if keys[pygame.K_UP]: + self.angle_x -= 0.05 + if keys[pygame.K_DOWN]: + self.angle_x += 0.05 + + # compute rotation matrices + rot_x = rot_3D(self.angle_x, "x") + rot_y = rot_3D(self.angle_y, "y") + rot = matmul(rot_y, rot_x) + projected: List[Tuple[float, float]] = [] + + center_x = self.size[0] / 2 + center_y = self.size[1] / 2 + + for corner in self.corners: + vec = [[corner[0]], [corner[1]], [corner[2]]] + # apply rotation + rotated = matmul(rot, vec) + x, y, z = rotated[0][0], rotated[1][0], rotated[2][0] + # orthographic projection + proj = project_ortho((x, y, z), scale=100) + projected.append((proj[0] + center_x, proj[1] + center_y)) + + self.projected = projected + return True + + + def draw_game(self) -> None: + self.screen.fill((0, 0, 0)) + for i, j in self.edges: + pygame.draw.line(self.screen, (0, 255, 0), self.projected[i], self.projected[j], 1) \ No newline at end of file diff --git a/spiel/game.py b/spiel/game.py new file mode 100644 index 0000000..cd99b94 --- /dev/null +++ b/spiel/game.py @@ -0,0 +1,38 @@ + +import pygame + + +class Game: + """Basic Pygame game loop. + + Subclasses **must** implement: + * ``update_game`` – update state, return ``False`` to quit. + * ``draw_game`` – render to the screen. + """ + + def __init__(self, title: str, fps: int, size: tuple[int, int]): + pygame.init() + self.screen = pygame.display.set_mode(size) + pygame.display.set_caption(title) + self.clock = pygame.time.Clock() + self.fps = fps + self.size = size + + def run(self) -> None: + running = True + while running: + for event in pygame.event.get(): + if event.type == pygame.QUIT: + running = False + if running: + running = self.update_game() + self.draw_game() + pygame.display.flip() + self.clock.tick(self.fps) + pygame.quit() + + def update_game(self) -> bool: + raise NotImplementedError + + def draw_game(self) -> None: + raise NotImplementedError diff --git a/spiel/projection.py b/spiel/projection.py new file mode 100644 index 0000000..a3788a4 --- /dev/null +++ b/spiel/projection.py @@ -0,0 +1,18 @@ + + +def project_ortho(point: tuple[float, float, float], scale: float = 1) -> tuple[float, float]: + """ projected 3D-Point orthogonal auf 2D (xy), z Koordinate wird ignoriert + + point : tuple[float, float, float] + 3-D point (x, y, z). + scale : float, optional + Scaling factor applied (default 1) + """ + 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]: + x, y, z = point + x_2d = x * focal_length / (z + camera_distance) * scale + y_2d = y * focal_length / (z + camera_distance) * scale + return (x_2d, y_2d) \ No newline at end of file