This commit is contained in:
kreischeran103444 committed 2026-11-04 22:06:16 +01:00
1 parent 93ee30229d
commit 572ee41e6f
8 files changed
+166 -7

No files matched your search

View File
Whitespace-only changes.
+53
View File
@@ -0,0 +1,53 @@
from __future__ import annotations
import pygame
from compute import rot_2D, matmul
from moon import Moon
# Apollo visual parameters
APOLLO_RADIUS = 2
APOLLO_COLOR = (255, 0, 0)
class Apollo(Moon):
def __init__(self, title: str = "Apollo", fps: int = 60, size: tuple[int, int] = (640, 400)) -> None:
super().__init__(title=title, fps=fps, size=size)
# Apollo starts on the positive x‑axis relative to the moon
self.offsetap: tuple[float, float] = (40.0, 0.0)
# Apollo moves twice as fast and opposite direction
self.delta_thetaap: float = -0.05
self.thetaap: float = 0.0
self.rot_apollo: list[list[float]] = rot_2D(self.theta)
def update_game(self) -> bool:
# Update moon first
super().update_game()
# Advance Apollo
self.thetaap += self.delta_thetaap
self.rot_apollo = rot_2D(self.thetaap)
point = [[self.offsetap[0]], [self.offsetap[1]]]
rel_pos = matmul(self.rot_apollo, point)
# Apollo's world position is moon's position plus relative vector
moon_pos = self.position_moon
self.position_apollo = (
moon_pos[0] + rel_pos[0][0],
moon_pos[1] + rel_pos[1][0],
)
return True
def draw_game(self) -> None:
# Draw base moon graphics
super().draw_game()
# Draw Apollo on the screen
pygame.draw.circle(
self.screen,
APOLLO_COLOR,
(int(self.position_apollo[0]), int(self.position_apollo[1])),
APOLLO_RADIUS,
)
if __name__ == "__main__":
apollo = Apollo()
apollo.run()
+165
View File
@@ -0,0 +1,165 @@
from __future__ import annotations
from collections.abc import Sequence
import math
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 rot3d(angle: float, axis: str) -> list[list[float]]:
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)
+37
View File
@@ -0,0 +1,37 @@
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
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
+73
View File
@@ -0,0 +1,73 @@
"""Moon orbital simulation demo.
This module defines :class:`Moon` which subclasses :class:`game.Game` and
uses :func:`compute.rot_2D` and :func:`compute.matmul` to animate a moon
orbiting the Earth.
The original repository contained a fully functional example, but the
``moon.py`` file was overwritten by another module during a previous
edit. The following implementation restores the expected behaviour.
"""
from __future__ import annotations
import pygame
from spiel.compute import rot_2D, matmul
from spiel.game import Game
EARTH_RADIUS = 30
MOON_RADIUS = 10
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
class Moon(Game):
def __init__(self, title: str = "Moon", fps: int = 60, size: Tuple[int, int] = (640, 400)) -> None:
super().__init__(title, fps, size)
# Earth centre – centre of the window
self.center: Tuple[int, int] = (size[0] // 2, size[1] // 2)
# Fixed orbit offset from the centre
self.offset: Tuple[float, float] = (150.0, 0.0)
# Angular speed (radians per frame)
self.delta_theta: float = 0.01
self.theta: float = 0.0
self.rot_moon: list[list[float]] = rot_2D(self.theta)
# Initial moon position
self.position_moon = (
self.center[0] + self.offset[0],
self.center[1] + self.offset[1],
)
def update_game(self) -> bool:
# Advance the angle and recompute the rotation matrix
self.theta += self.delta_theta
self.rot_moon = rot_2D(self.theta)
# Rotate the fixed offset vector
point = [[self.offset[0]], [self.offset[1]]]
result = matmul(self.rot_moon, point)
# Translate back to screen coordinates
self.position_moon = (
self.center[0] + result[0][0],
self.center[1] + result[1][0],
)
return True
def draw_game(self) -> None:
self.screen.fill(BLACK)
pygame.draw.circle(self.screen, BLUE, self.center, EARTH_RADIUS)
pygame.draw.circle(
self.screen,
WHITE,
(int(self.position_moon[0]), int(self.position_moon[1])),
MOON_RADIUS,
)
if __name__ == "__main__":
moon = Moon()
moon.run()