würfel läuft

This commit is contained in:
kreischeran103444 committed 2026-11-05 01:25:22 +01:00
commit 3cc07d2575
13 files changed
+526

No files matched your search

View File
Whitespace-only changes.
+184
View File
@@ -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)
+81
View File
@@ -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)
+38
View File
@@ -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
+18
View File
@@ -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)