From 83002280594a3b14e261f884083278f36c6d4adb Mon Sep 17 00:00:00 2001 From: rajan Date: Wed, 28 Oct 2026 20:01:19 +0100 Subject: [PATCH] =?UTF-8?q?Rotierender=20W=C3=BCrfel=20mit=20CubeGame?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 2 + .idea/.gitignore | 8 + .../inspectionProfiles/profiles_settings.xml | 6 + .idea/misc.xml | 10 + .idea/modules.xml | 8 + .idea/wurfel.iml | 10 + install_dependencies.py | 200 ++++++++++++++++++ main.py | 4 + pyproject.toml | 7 + spiel/__init__.py | 0 spiel/__pycache__/__init__.cpython-313.pyc | Bin 0 -> 152 bytes spiel/__pycache__/compute.cpython-313.pyc | Bin 0 -> 7495 bytes spiel/__pycache__/cube_game.cpython-313.pyc | Bin 0 -> 3475 bytes spiel/__pycache__/game.cpython-313.pyc | Bin 0 -> 2989 bytes spiel/compute.py | 196 +++++++++++++++++ spiel/cube_game.py | 47 ++++ spiel/game.py | 53 +++++ 17 files changed, 551 insertions(+) create mode 100644 .gitignore create mode 100644 .idea/.gitignore create mode 100644 .idea/inspectionProfiles/profiles_settings.xml create mode 100644 .idea/misc.xml create mode 100644 .idea/modules.xml create mode 100644 .idea/wurfel.iml 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/__pycache__/__init__.cpython-313.pyc create mode 100644 spiel/__pycache__/compute.cpython-313.pyc create mode 100644 spiel/__pycache__/cube_game.cpython-313.pyc create mode 100644 spiel/__pycache__/game.cpython-313.pyc 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..fc857fc --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +git add . +git commit -m "Rotierender Würfel mit CubeGame" \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..13566b8 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Editor-based HTTP Client requests +/httpRequests/ +# 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/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..5a1065a --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..47f5054 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/wurfel.iml b/.idea/wurfel.iml new file mode 100644 index 0000000..cbf473a --- /dev/null +++ b/.idea/wurfel.iml @@ -0,0 +1,10 @@ + + + + + + + + + + \ 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..f1ca147 --- /dev/null +++ b/main.py @@ -0,0 +1,4 @@ +from spiel.cube_game import CubeGame + +if __name__ == "__main__": + CubeGame().run() \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..79c55f1 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,7 @@ +[project] +name = "wurfel" +version = "0.1.0" +dependencies = ["pygame"] + +[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/__pycache__/__init__.cpython-313.pyc b/spiel/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ba7cceed09f83cbf95942321cf5a568eafaff18 GIT binary patch literal 152 zcmey&%ge<81fq72vOx4>5CH>>P{wB#AY&>+I)f&o-%5reCLr%KNa~ikvsFxJacWU< zOi^N1VqQ!@WpYMhQEos{epYI7NpVbhX;E5gPE2t@CXkGe&&NnS?GIJ5Ka^5!Rem-ZuNU?5L-A%S;om6IrW{u)$+@?u zhXzUUZW_($+xMP(&V8KoopZ0Am6iDrJhtJlZ#LB-^gH@tK5nDHJuBD{`WW$uAfDrG z7r8fW#D;0ve$h_s@OE5uyy+kgj3%7$=bCVLLSH9zr$6H1_wmj~bkjk+{C?iWN}n;Z!kb$r-t+j{fuyuZj*#vkGXOj2;7oG%+3L+BhQgb?aR zd~lQlS`O4kDxg%szC(;wGFk=HK|&M07Bo>Y5jp}hr4R5{v-TRGHYzg?Ep?a3EN(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zk!XbXnck^Z%7YRfNgj~-zxC`Z|ITRGjhoG Pt3$4lBhFv-b3p$W+37)k literal 0 HcmV?d00001 diff --git a/spiel/__pycache__/cube_game.cpython-313.pyc b/spiel/__pycache__/cube_game.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9e7ee34cde06a13e6225ec8deba2680d4ca1ab88 GIT binary patch literal 3475 zcmZ`5TTC0-^^Rx89^)~DS7RR9m^?O`6^|;IC2d(!UV&iZupXR7HQAA424iY$_s+Np z^au5$!d0VWrAAGqs0-3c*_En_s`~*_)a0Wd`CON@(A!k2wjULL$&&4+U)ytLJSJi3 zk>=cU&pG$rbI)t;p5I?Z0P4>Db3WuI(Kr9n`*MPV~RHAZWLUDA3xp5bDjq{Wr z7pM?K9v>FR-P9c>hFF9$Ue|!*j8Gi z84#s@-0<7ce=PmtToNV~K+6#JB7ok5&`%S}sj!dAQC{_^QjCN+m2W2V(!4OwQ9*T0 ziy@aP07szivRt&~)B_0sE8gL#_asrgOd2X&(=mR#jj%lgRW}PXn{*DvgV8JKvAsz^ z{oEZAhtY;9Ax5r({7PMncd`fakBgBE-pT@NR?aK}`3SPg?kR9tB;{x-A`^{5UZ+gb zv~)IYY8vw-vZ;)&-EfFS=FR8QS<}$Y%z(aN=$Tn2nrSnmGk!L204KeqGq0v4GYP}c zGy}~K0xYw$L*Jf`89FtlX<|N+ot|7w&L!x=q@C8r^z{Or)icvZJ`Fete$i6kn9lqn zJqmlUTE|tLj&vGS z>0nMD0MzM#wH-ioKyetZOeMCK1(@##;Qv@~=yP){m5KuL>Q|<2rzG<&XPx$kkKM;UKyA9w9ywBq>pGM;N!rxErq}I3`Co ze0y&JIsuAzpaH;jp%3S3RV&~>B6mdC2oAC~;(Ga64!S3XC-N~g2~ z`d)+yVJ$XEn^58jYtaj%V^b)b7&$*h(FqiDo4Ji7)%7fsa69Z&wAorQbSWAciK-Nh zfSrd1CPtV$kp ztD9F#XTznoa49fRk|u7-PwSiRy}8WOUCUs{oN z0<9nTe&yQ^w3ho|RfWxhbSDFyW4{5|P&T7Sn%UmeyDccN{`>tKN z@k+Cv;^A4KfKJ&KXb(i;B8rcOfWw5@bSA^Z!HI#PFcU|HM@LlJZV6^+;yM#D>8#Gg z(dfuX#3~Pp|5@fmq4h^r1iK*t zC%?53df30&|M*1dJCXnJE`RlNp0osCNW@!>&w!>sOD$H4z|#-Ah1D3W%P9Pkr+YYv zX6^QYL~*5;A++h+kTuZtusubTDtrNDq4~fIs7lioax(>Z1Zhmxv>z4{nX;rt(`M7u zFwtMxoTk~&6yaJfm!U&=sO5o1cmrX}NNNewr0Ht~Q-@~}^Os*pNj;O%G=;N02u6_a z+U~<>QbhPqHBJC}`BUopV)AB>IH$}%VxLO`UL@G-Pu~DRNFE2ThFP^ zWNsl3C)=$MQ^)RyRkjrSEX9PUZzCE*6h<_Ps25QeBFiRxaM|Ysfnrjh?Vf)6eVF0} zi~&H;c#h-#M*ROKy(QB7chd5?!24Xwp3f!0>sl6{RS|E)vbZDFBJv@Um&F(EX0CO` K{DQz>9q~VsJ))`r literal 0 HcmV?d00001 diff --git a/spiel/__pycache__/game.cpython-313.pyc b/spiel/__pycache__/game.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9220a066974d22534da983377221fbcae2416249 GIT binary patch literal 2989 zcmb7G&2JM&6rc6(I_vlo9GegaFlqQOD4~>6wE?wNX`xkxMZH*}ilx=o-Z&c;+sv*@ z(?i9n3Mh!?5JiUsg2=uxBJ*c`jt1q*Tt;|?oovw= zaZE;f^+`bF2O0LBW_&V)c+Tc9-b;CU#nf1G)ImwlF zzPaFz>`G@lLY^4jTA731kgFjR=y}%4B;(6c+%OZcMN78~&F1H7rY)HI*P89GEtbI< zTd;IM@q$q;Ubn>}`}j(h?Kg{5(<&JO^fhCS;w}`8(*S^p?x&&IXD-YX@}@@30#z5( zO5w_4abBf2uF&d&RdRU^9_gn_Zc0C5|={N1KV`O9IU9jl*ZCog7;d?gh7D87X?fh7MA~ zXxRi|mCOPh0);%U=# z51I)udRT%)7(-q^jGE^FZj((ZazA)CxEw|yawpP~CK}Sj`kN1D9?U$JrZ>CjPCY99q;KfWd{+MhPH{0aL{S-UUh%qfr6Smm zXkTg-OPN2?O?rDQY}qkECfnay~RYD0_9y?p@L#mt2Nu<%In8b^K$^WPLaL8 zCCAnlRuB@vAVM)f}e zcjpaGm~Q|;AfRX#Rtl}ekw)Uk)5Ni*kJ|Blt@vakKDnN6#ZNZlCx6*D{z4?lYD`&kGgKnaCpSZG*o&Yl$9#Vg?rgeD!EdR+>ipjFey(t*5 z_b~Um!*LY#MgbtBgR%QFcV>P_{+Rkc)eKIyW0WKJs}O#87O!rQ-qfOp zVcL$d9lI_bi#z54Y&gie7ohi<^;tlt4SHiTSm}vlry%fS1=CL%|Cq0oynS&WWE2|W1sZ&+)ZF62ZyrS8R z@7a0yW_@L&H9T!vpd_!X&O{Z#B>1>eQGfpSPuZq`+!GZR&mIh~polx3|_RTPSG zraiu-aSYRzWfDb>=s5s8p(v)MLa|p=%cA-hbxSkB28NFvoV~bIz%Bwt+B^mDE%{UM zi>a*`FTS%ClEedBBb=Dr@(bd~R)_}}<^cShcBz|8#%jF0|u literal 0 HcmV?d00001 diff --git a/spiel/compute.py b/spiel/compute.py new file mode 100644 index 0000000..ea87ffd --- /dev/null +++ b/spiel/compute.py @@ -0,0 +1,196 @@ +"""Utility functions for matrix operations.""" + +from __future__ import annotations + +import math + +from tabulate import tabulate + +Matrix = list[list[int | float]] + + +def transpose(matrix: Matrix) -> Matrix: + """Return the transpose of a matrix. + + Args: + matrix: Rectangular, non-empty matrix in row-major format. + + Returns: + The transposed matrix. + + Raises: + ValueError: If the matrix is empty or has irregular rows. + """ + if not matrix: + raise ValueError("Cannot transpose an empty matrix") + row_length = len(matrix[0]) + if row_length == 0: + raise ValueError("Matrix rows must have at least one column") + for row in matrix: + if len(row) != row_length: + raise ValueError("Inconsistent row lengths; matrix must be rectangular") + return [list(column) for column in zip(*matrix)] + + +def matmul(a: Matrix, b: Matrix) -> Matrix: + """Return the matrix product of two matrices. + + Args: + a: Matrix with m rows and n columns. + b: Matrix with n rows and p columns. + + Returns: + The product matrix with m rows and p columns. + + Raises: + ValueError: If a matrix is empty or the inner dimensions do not match. + """ + if not a or not b: + raise ValueError("Both matrices must be non-empty") + if not a[0] or not b[0]: + raise ValueError("Matrices must have at least one column") + + rows_a, cols_a = len(a), len(a[0]) + rows_b, cols_b = len(b), len(b[0]) + + if cols_a != rows_b: + raise ValueError( + f"Inner matrix dimensions must agree: got {cols_a} and {rows_b}" + ) + + result: Matrix = [] + for i in range(rows_a): + result_row: list[int | float] = [] + for j in range(cols_b): + total: int | float = 0 + for k in range(cols_a): + total += a[i][k] * b[k][j] + result_row.append(total) + result.append(result_row) + return result + + +def rot_2D(theta: float) -> Matrix: + """Create a 2D rotation matrix. + + Args: + theta: Rotation angle in radians. Positive values rotate + counter-clockwise. + + Returns: + A 2x2 rotation matrix [[cos, -sin], [sin, cos]]. + """ + return [ + [math.cos(theta), -math.sin(theta)], + [math.sin(theta), math.cos(theta)], + ] + +def project_ortho( + point: tuple[float, float, float], scale: float = 1 +) -> tuple[float, float]: + """Projiziert einen 3D-Punkt orthogonal auf die x-y-Ebene. + + Die z-Koordinate wird ignoriert. x und y werden mit scale multipliziert. + + Args: + point: Der 3D-Punkt (x, y, z). + scale: Skalierungsfaktor für den projizierten Punkt. + + Returns: + Der 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 x-y-Ebene. + + x_2d = x * focal_length / (z + camera_distance) * scale + y_2d = y * focal_length / (z + camera_distance) * scale + + Args: + point: Der 3D-Punkt (x, y, z). + focal_length: Brennweite, steuert die Stärke der Perspektive. + scale: Skalierungsfaktor für den projizierten Punkt. + camera_distance: Offset für die Kameraposition auf der z-Achse. + + Returns: + Der 2D-Punkt (x_2d, y_2d). + + Raises: + ValueError: Wenn z + camera_distance gleich 0 ist. + """ + x, y, z = point + depth = z + camera_distance + if depth == 0: + raise ValueError("z + camera_distance darf nicht 0 sein") + return (x * focal_length / depth * scale, y * focal_length / depth * scale) + + +def rot_3D(angle: float, axis: str) -> list[list[float]]: + """Gibt die 3D-Rotationsmatrix für eine Drehung um eine Koordinatenachse zurück. + + Rotation um die x-Achse: + [[1, 0, 0], [0, cos(a), -sin(a)], [0, sin(a), cos(a)]] + Rotation um die y-Achse: + [[cos(a), 0, sin(a)], [0, 1, 0], [-sin(a), 0, cos(a)]] + Rotation um die z-Achse: + [[cos(a), -sin(a), 0], [sin(a), cos(a), 0], [0, 0, 1]] + + Args: + angle: Drehwinkel a im Bogenmaß. + axis: Drehachse, "x", "y" oder "z". + + Returns: + Die 3x3-Rotationsmatrix als verschachtelte Liste. + + Raises: + ValueError: Wenn axis nicht "x", "y" oder "z" ist. + """ + cos_a = math.cos(angle) + sin_a = math.sin(angle) + if axis == "x": + return [[1, 0, 0], [0, cos_a, -sin_a], [0, sin_a, cos_a]] + if axis == "y": + return [[cos_a, 0, sin_a], [0, 1, 0], [-sin_a, 0, cos_a]] + if axis == "z": + return [[cos_a, -sin_a, 0], [sin_a, cos_a, 0], [0, 0, 1]] + raise ValueError("axis muss 'x', 'y' oder 'z' sein") + + +if __name__ == "__main__": + matrix_a = [ + [3, 4, -1, 4], + [-2, 2, 5, 1], + ] + matrix_b = [ + [1, 3, -2], + [2, 5, 1], + [-1, 4, -4], + [2, 3, 6], + ] + assert matmul(matrix_a, matrix_b) == [[20, 37, 26], [-1, 27, -8]] + assert matmul([[1, 2]], [[3], [4]]) == [[11]] + + assert transpose([[1, 2, 3], [4, 5, 6]]) == [[1, 4], [2, 5], [3, 6]] + + for bad_matrix in ([], [[1, 2], [3, 4, 5]]): + try: + transpose(bad_matrix) + except ValueError: + pass + else: + raise AssertionError("ValueError erwartet") + + point = [[1.0], [0.0]] + rotated = matmul(rot_2D(math.pi / 2), point) + assert math.isclose(rotated[0][0], 0.0, abs_tol=1e-9) + assert math.isclose(rotated[1][0], 1.0, abs_tol=1e-9) + assert rot_2D(0) == [[1.0, 0.0], [0.0, 1.0]] + print(tabulate(rot_2D(1.0))) + print("Alle Tests bestanden.") diff --git a/spiel/cube_game.py b/spiel/cube_game.py new file mode 100644 index 0000000..e2f3846 --- /dev/null +++ b/spiel/cube_game.py @@ -0,0 +1,47 @@ +import pygame + +from spiel.compute import matmul, project_ortho, rot_3D +from spiel.game import Game + +CORNERS = [ + (-1, -1, -1), (1, -1, -1), (1, 1, -1), (-1, 1, -1), + (-1, -1, 1), (1, -1, 1), (1, 1, 1), (-1, 1, 1), +] +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), +] +GREEN = (0, 255, 0) +BLACK = (0, 0, 0) +SCALE = 100 +SPEED = 0.02 + + +class CubeGame(Game): + def __init__(self, title="3D Cube", fps=60, size=(640, 400)) -> None: + super().__init__(title, fps, size) + self.angle_x = 0.0 + self.angle_y = 0.0 + self.points_2d: list[tuple[float, float]] = [] + + def update_game(self) -> bool: + keys = pygame.key.get_pressed() + self.angle_x += SPEED * (keys[pygame.K_DOWN] - keys[pygame.K_UP]) + self.angle_y += SPEED * (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) + rotation = matmul(rot_3D(self.angle_y, "y"), rot_3D(self.angle_x, "x")) + width, height = self.screen.get_size() + self.points_2d = [] + for x, y, z in CORNERS: + rx, ry, rz = (row[0] for row in matmul(rotation, [[x], [y], [z]])) + px, py = project_ortho((rx, ry, rz), SCALE) + self.points_2d.append((px + width / 2, py + height / 2)) + return True + + def draw_game(self) -> None: + self.screen.fill(BLACK) + for start, end in EDGES: + pygame.draw.line( + self.screen, GREEN, self.points_2d[start], self.points_2d[end] + ) + super().draw_game() \ No newline at end of file diff --git a/spiel/game.py b/spiel/game.py new file mode 100644 index 0000000..0c201a2 --- /dev/null +++ b/spiel/game.py @@ -0,0 +1,53 @@ +import pygame + +class Game: + + def __init__(self, title, fps=60, size=(640, 400)): + self.title = title + self.fps = fps + self.size = size + self.clock = pygame.time.Clock() + self.dt = 0 + self.screen = None + + def init_game(self): + pygame.init() + pygame.display.set_caption(self.title) + self.screen = pygame.display.set_mode(self.size) + + + def game_loop(self): + while True: + # Berechnung der Zeitdifferenz seit dem letzten Frame in Sekunden + 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): + pygame.quit() + + def event_handling(self): # bleibt in der Unterklasse unverändert + for event in pygame.event.get(): + if not self.handle_event(event): + return False + return True + + def handle_event(self, event): # wird in der Unterklasse überschrieben + if event.type == pygame.QUIT: + return False + return True + + def update_game(self): + return True + + def draw_game(self): + pygame.display.flip() + + def run(self): + self.init_game() + self.game_loop() + self.exit_game() +