From 5e063d06b19e9ebe4485ce0c51ee8d645decadb2 Mon Sep 17 00:00:00 2001 From: Lena Date: Wed, 28 Oct 2026 23:42:33 +0100 Subject: [PATCH] =?UTF-8?q?W=C3=BCrfel=20anlegen?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 6 + install_dependencies.py | 200 ++++++++++++++++++++++++++++ main.py | 4 + pyproject.toml | 7 + spiel/__init__.py | 0 spiel/compute.py | 281 ++++++++++++++++++++++++++++++++++++++++ spiel/cube_game.py | 0 spiel/game.py | 41 ++++++ 8 files changed, 539 insertions(+) create mode 100644 .gitignore create mode 100644 install_dependencies.py create mode 100644 main.py create mode 100644 pyproject.toml create mode 100644 spiel/__init__.py create mode 100644 spiel/compute.py create mode 100644 spiel/cube_game.py create mode 100644 spiel/game.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..457fcd7 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.venv/ +__pycache__/ +.env +.vscode/ +.DS_Store +opencode.json \ No newline at end of file diff --git a/install_dependencies.py b/install_dependencies.py new file mode 100644 index 0000000..36be080 --- /dev/null +++ b/install_dependencies.py @@ -0,0 +1,200 @@ +#!/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..b97c6f2 --- /dev/null +++ b/main.py @@ -0,0 +1,4 @@ + + + +#source .venv/bin/activate \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..84298ef --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,7 @@ +[project] +name = "wuerfel" +version = "0.1.0" +dependencies = ["pygame", "tabulate"] +[project.optional-dependencies] +dev = [] + 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..5ff4e82 --- /dev/null +++ b/spiel/compute.py @@ -0,0 +1,281 @@ +"""Utility functions for matrix operations. + +This module contains: +* ``matmul`` – standard matrix multiplication. +* ``transpose`` – row↔column swapping. +* ``rotate`` – 90‑degree clockwise rotations. + +All functions use type hints and raise informative errors where +dimensions are incompatible or matrices are non‑rectangular. +""" + +from __future__ import annotations + +from tabulate import tabulate + +Matrix = list[list[int | float]] + + +def matmul(a: Matrix, b: Matrix) -> Matrix: + """Return the matrix product a @ b. + + Parameters + ---------- + a : Matrix + Left‑hand matrix. + b : Matrix + Right‑hand matrix. + + Returns + ------- + Matrix + Product matrix. + + Raises + ------ + ValueError + If matrices are not rectangular or dimensions are incompatible. + """ + + def _rect(mat: Matrix) -> bool: + return all(len(row) == len(mat[0]) for row in mat) + + if not a or not b: + raise ValueError("matrices may not be empty") + if not _rect(a) or not _rect(b): + raise ValueError("input matrices must be rectangular") + + r1, c1 = len(a), len(a[0]) + r2, c2 = len(b), len(b[0]) + if c1 != r2: + raise ValueError("first matrix columns must equal second matrix rows") + + result: Matrix = [[0 for _ in range(c2)] for _ in range(r1)] + for i in range(r1): + for j in range(c2): + s = 0 + for k in range(c1): + s += a[i][k] * b[k][j] + result[i][j] = s + return result + + +def transpose(matrix: Matrix) -> Matrix: + """Return the transpose of a 2‑D matrix. + + The transpose operation swaps rows and columns: each row in the + result is a column from the input matrix. + + Parameters + ---------- + matrix : Matrix + Two‑dimensional list of numbers. All rows must contain the + same number of columns. + + Returns + ------- + Matrix + Transposed matrix. + + Raises + ------ + ValueError + If *matrix* is empty or if the rows have differing lengths. + """ + if not matrix: + raise ValueError("transpose requires a non‑empty matrix") + if any(len(row) != len(matrix[0]) for row in matrix): + raise ValueError("matrix must be rectangular to transpose") + rows, cols = len(matrix), len(matrix[0]) + return [[matrix[i][j] for i in range(rows)] for j in range(cols)] + + +def rot_2D(theta: float) -> list[list[float]]: + """Return the 2‑D rotation matrix for angle *theta* in radians. + + The matrix is + ``[[cos(θ), -sin(θ)], + [sin(θ), cos(θ)]]`` + where θ is interpreted as a clockwise rotation. + + Parameters + ---------- + theta : float + Rotation angle in radians (clockwise). + + Returns + ------- + list[list[float]] + 2x2 rotation matrix. + """ + import math + + # Treat theta as radians directly + rad = theta + cos_t = math.cos(rad) + sin_t = math.sin(rad) + return [[cos_t, -sin_t], [sin_t, cos_t]] + + +def rotate(matrix: Matrix, degrees: float) -> Matrix: + """Rotate the matrix clockwise by arbitrary degrees. + + The function maps each element to a new integer coordinate that + results from rotating the original coordinate around the centre of + the matrix using a 2×2 rotation matrix. + + Elements that are mapped outside the original bounds are discarded. + In case multiple elements map to the same location the last one + wins. + + Parameters + ---------- + matrix : Matrix + degrees : float + Rotation angle in degrees (clockwise). + + Returns + ------- + Matrix + """ + + if not matrix: + return [] + n_rows, n_cols = len(matrix), len(matrix[0]) + # rotation matrix + import math + + r = rot_2D(math.radians(degrees)) + cos_t, sin_t = r[0][0], r[1][0] # cos and sin from 2x2 matrix + # centre of the matrix (half‑index) + c_row = (n_rows - 1) / 2.0 + c_col = (n_cols - 1) / 2.0 + # create empty result + result = [[0 for _ in range(n_cols)] for _ in range(n_rows)] + for i in range(n_rows): + for j in range(n_cols): + # coordinates relative to centre + y = i - c_row + x = j - c_col + # rotate + new_x = cos_t * x - sin_t * y + new_y = sin_t * x + cos_t * y + # back to integer index + new_i = round(new_y + c_row) + new_j = round(new_x + c_col) + if 0 <= new_i < n_rows and 0 <= new_j < n_cols: + result[new_i][new_j] = matrix[i][j] + return result + + +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". + """ + + import math + + 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 project_ortho( + point: tuple[float, float, float], scale: float = 1 +) -> tuple[float, float]: + """Project a 3‑D point orthogonally onto the xy‑plane. + + Parameters + ---------- + point : tuple[float, float, float] + Coordinates (x, y, z) of the point. + scale : float, optional + Scaling factor applied to the projected x and y. + + Returns + ------- + tuple[float, float] + The projected (x, y) after scaling. + """ + + 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]: + """Lässt entfernte Punkte kleiner erscheinen. + + Parameters + ---------- + point : tuple[float, float, float] + Coordinates (x, y, z) of the point. + focal_length: float + Wie stark die Perspektive sichtbar ist (wie Brennweite) + scale : float, optional + Scaling factor applied to the projected x and y. + camera_distance: float + Entfernung der Kamera + + + Returns + ------- + tuple[float, float] + The projected (x, y) after sizing. + """ + + x2d = ((point[0] * focal_length) / (point[2] + camera_distance)) * scale + y2d = ((point[1] * focal_length) / (point[2] + camera_distance)) * scale + + return (x2d, y2d) + + +if __name__ == "__main__": + # matmul tests + a1 = [[1, 2], [3, 4]] + b1 = [[5, 6], [7, 8]] + assert matmul(a1, b1) == [[19, 22], [43, 50]], "matmul example 1 failed" + a2 = [[1], [2], [3]] + b2 = [[4, 5, 6]] + assert matmul(a2, b2) == [[4, 5, 6], [8, 10, 12], [12, 15, 18]], ( + "matmul example 2 failed" + ) + + # transpose test + mat = [[1, 2, 3], [4, 5, 6]] + assert transpose(mat) == [[1, 4], [2, 5], [3, 6]], "transpose failed" + + # rotation tests + mat3 = [[1, 2], [3, 4], [5, 6]] + assert rotate(mat3, 90) == [[5, 3, 1], [6, 4, 2]], "rotate 90 failed" + assert rotate(mat3, 180) == [[6, 5], [4, 3], [2, 1]], "rotate 180 failed" + assert rotate(mat3, 270) == [[2, 4, 6], [1, 3, 5]], "rotate 270 failed" + assert rotate(mat3, 0) == mat3, "rotate 0 failed" + + print(tabulate(rot_2D(1.0))) diff --git a/spiel/cube_game.py b/spiel/cube_game.py new file mode 100644 index 0000000..e69de29 diff --git a/spiel/game.py b/spiel/game.py new file mode 100644 index 0000000..1b92e62 --- /dev/null +++ b/spiel/game.py @@ -0,0 +1,41 @@ +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 handle_event(self, event: pygame.event.Event) -> None: + """Handle a single pygame event. Override in subclasses.""" + pass + + def run(self) -> None: + running = True + while running: + for event in pygame.event.get(): + self.handle_event(event) + if event.type == pygame.QUIT: + running = False + running = self.update_game() and running + 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