Erster Stand: compute.py, moon.py, apollo.py

This commit is contained in:
Tara Seidler committed 2026-10-22 14:24:19 +02:00
commit 4afa4a1fb4
12 files changed
+279

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
.venv/
.venv1/
__pycache__/
.env
+5
View File
@@ -0,0 +1,5 @@
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
+6
View File
@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$">
<excludeFolder url="file://$MODULE_DIR$/.venv1" />
</content>
<orderEntry type="jdk" jdkName="Python 3.14 (matrixmania)" jdkType="Python SDK" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="Python 3.14 (matrixmania)" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.14 (matrixmania)" project-jdk-type="Python SDK" />
</project>
+8
View File
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/matrixmania.iml" filepath="$PROJECT_DIR$/.idea/matrixmania.iml" />
</modules>
</component>
</project>
Generated
+6
View File
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>
+4
View File
@@ -0,0 +1,4 @@
# 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`.
+42
View File
@@ -0,0 +1,42 @@
"""Die Raumkapsel Apollo kreist um den Mond."""
from compute import matmul, rot_2D
from moon import ANGLE, MOON_DIST, Moon, MOON_RADIUS
APOLLO_DIST = 35 # Abstand Mond -> Apollo
APOLLO_RADIUS = 6
RED = (255, 0, 0)
class Apollo(Moon):
"""Apollo kreist doppelt so schnell und rückwärts um den Mond."""
def __init__(self) -> None:
"""Legt zwei Bahnen an: Mond um Erde, Apollo um Mond."""
super().__init__(title="Apollo")
self.mond_pos = [MOON_DIST, 0.0] # Mond relativ zur Erde
self.pos = [APOLLO_DIST, 0.0] # Apollo relativ zum Mond
self.mond_winkel = ANGLE # normale Drehrichtung
self.angle = -2 * ANGLE # doppelte, entgegengesetzte Drehung
def update_game(self) -> bool:
"""Dreht Mond und Apollo jeweils ein Stück weiter."""
self.mond_pos = matmul(rot_2D(self.mond_winkel), self.mond_pos)
self.pos = matmul(rot_2D(self.angle), self.pos)
return True
def draw_game(self) -> None:
"""Zeichnet Erde, Mond und Apollo."""
self.clear()
self.draw_earth()
mond_abs = self.absolut(self.mond_pos)
self.draw_body(mond_abs, MOON_RADIUS, (255, 255, 255))
# Apollo: relativ zum Mond, nicht zur Erde!
apollo_abs = (mond_abs[0] + self.pos[0], mond_abs[1] + self.pos[1])
self.draw_body(apollo_abs, APOLLO_RADIUS, RED)
self.display()
if __name__ == "__main__":
apollo = Apollo()
apollo.start() # bzw. die Start-Methode eurer Game-Klasse
+113
View File
@@ -0,0 +1,113 @@
"""Utilities for numeric matrix operations.
This module provides matrix helpers (matmul, transpose, rot_2D)
for the MatrixMania project.
"""
from __future__ import annotations
from math import cos, sin
from typing import List
from tabulate import tabulate
Matrix = List[List[float]]
def matmul(a: Matrix, b: Matrix) -> Matrix:
"""Return the product of two matrices.
Parameters
----------
a: list[list[float]]
Left matrix of shape ``(m, n)``.
b: list[list[float]]
Right matrix of shape ``(n, p)``.
Returns
-------
list[list[float]]
Resultant matrix of shape ``(m, p)``.
"""
if not isinstance(a, list) or not isinstance(b, list):
raise ValueError("Both arguments must be 2-D lists of numbers.")
if not a or not a[0] or not b or not b[0]:
raise ValueError("Matrices must be non-empty and properly sized.")
a_rows, a_cols = len(a), len(a[0])
b_rows, b_cols = len(b), len(b[0])
if any(len(row) != a_cols for row in a):
raise ValueError("All rows in matrix 'a' must have the same length.")
if any(len(row) != b_cols for row in b):
raise ValueError("All rows in matrix 'b' must have the same length.")
if a_cols != b_rows:
raise ValueError(
f"Inner dimensions mismatch: "
f"a has {a_cols} columns, b has {b_rows} rows."
)
b_t = list(map(list, zip(*b)))
result: Matrix = []
for row_a in a:
res_row: List[float] = []
for col_b in b_t:
dot = sum(x * y for x, y in zip(row_a, col_b))
res_row.append(dot)
result.append(res_row)
return result
def transpose(matrix: Matrix) -> Matrix:
"""Return the transpose of a 2-D list.
Parameters
----------
matrix: list[list[float]]
The matrix to transpose. All rows must have equal length.
Returns
-------
list[list[float]]
The transposed matrix.
"""
if not isinstance(matrix, list) or not matrix:
raise ValueError("Matrix must be a non-empty 2-D list.")
if any(not isinstance(row, list) for row in matrix):
raise ValueError("Matrix must contain rows that are lists.")
row_len = len(matrix[0])
if any(len(row) != row_len for row in matrix):
raise ValueError("All rows in the matrix must have the same length.")
return list(map(list, zip(*matrix)))
def rot_2D(winkel: float) -> Matrix:
"""Return the 2-D rotation matrix for an angle in radians.
Parameters
----------
winkel: float
Rotation angle in radians. Positive values rotate
counter-clockwise.
Returns
-------
list[list[float]]
The 2x2 rotation matrix.
"""
return [[cos(winkel), -sin(winkel)], [sin(winkel), cos(winkel)]]
def print_matrix(matrix: Matrix) -> None:
"""Print a matrix as a nicely formatted table."""
print(tabulate(matrix, tablefmt="grid"))
if __name__ == "__main__":
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
print_matrix(matmul(a, b))
print_matrix(rot_2D(1.0))
+70
View File
@@ -0,0 +1,70 @@
"""Der Mond kreist um die Erde."""
import pygame
from compute import matmul, rot_2D
from game import Game
EARTH_RADIUS = 30
MOON_RADIUS = 10
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
MOON_DIST = 120 # Abstand Erde -> Mond
ANGLE = 0.02 # Drehwinkel pro Bild
class Moon(Game):
"""Der Mond kreist um die Erde."""
def __init__(
self,
title: str = "Moon",
fps: int = 60,
size: tuple[int, int] = (640, 400),
) -> None:
"""Legt Startposition, Drehwinkel und Rotationsmatrix fest."""
super().__init__(title, fps, size)
self.center = (size[0] / 2, size[1] / 2) # Erdposition
self.angle = self.drehwinkel() # Drehwinkel pro Bild
self.pos = self.startposition() # Vektor relativ zur Erde
def drehwinkel(self) -> float:
"""Winkel, um den pro Bild weitergedreht wird (Hook für Apollo)."""
return ANGLE
def startposition(self) -> list[float]:
"""Startposition als Vektor relativ zum Mittelpunkt."""
return [MOON_DIST, 0.0]
def update_game(self) -> bool:
"""Dreht den Mond ein Stück weiter."""
self.pos = self.drehe(self.pos)
return True
def drehe(self, vektor: list[float]) -> list[float]:
"""Dreht einen Vektor mit der Rotationsmatrix weiter."""
return matmul(rot_2D(self.angle), vektor)
def absolut(self, vektor: list[float]) -> tuple[float, float]:
"""Rechnet einen relativen Vektor in Bildschirmkoordinaten um."""
return (self.center[0] + vektor[0], self.center[1] + vektor[1])
def draw_game(self) -> None:
"""Zeichnet Erde und Mond."""
self.clear() # falls Game das anders macht: anpassen
self.draw_earth()
self.draw_body(self.absolut(self.pos), MOON_RADIUS, WHITE)
self.display() # Bild anzeigen
def draw_earth(self) -> None:
"""Zeichnet die Erde ins Zentrum."""
pygame.draw.circle(self.screen, BLUE, self.center, EARTH_RADIUS)
def draw_body(
self, pos: tuple[float, float],
radius: int, farbe: tuple[int, int, int],
) -> None:
"""Zeichnet einen Himmelskörper an einer Position."""
pygame.draw.circle(self.screen, farbe, pos, radius)
+4
View File
@@ -0,0 +1,4 @@
[project]
name = "matrixmania"
version = "0.1.0"
dependencies = ["tabulate", "ruff"]