files added, compute modified
This commit is contained in:
1 parent
806434d813
commit
ebd75fe26e
9 files changed
+527
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,145 @@
|
||||
"""Compute operations for matrices.
|
||||
|
||||
This module provides public functions for matrix multiplication, transposition,
|
||||
matrix rotation, and generating 2D and 3D rotation matrices as well as projections.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from typing import List
|
||||
|
||||
|
||||
def matmul(
|
||||
matrix_a: List[List[float]], matrix_b: List[List[float]]
|
||||
) -> List[List[float]]:
|
||||
"""Multiply two 2D matrices.
|
||||
|
||||
Both matrices are expected to be non‑empty and to have consistent row
|
||||
lengths. The number of columns in ``matrix_a`` must equal the number of
|
||||
rows in ``matrix_b``.
|
||||
|
||||
Args:
|
||||
matrix_a: A matrix of shape (m, n) represented as a list of m rows.
|
||||
matrix_b: A matrix of shape (n, p) represented as a list of n rows.
|
||||
|
||||
Returns:
|
||||
A new matrix of shape (m, p) containing the product ``matrix_a @ matrix_b``.
|
||||
|
||||
Raises:
|
||||
ValueError: If either matrix is empty or dimensions do not match.
|
||||
"""
|
||||
if not matrix_a or not matrix_b:
|
||||
raise ValueError("Input matrices must not be empty.")
|
||||
|
||||
n_cols_a = len(matrix_a[0])
|
||||
|
||||
if any(len(row) != n_cols_a for row in matrix_a):
|
||||
raise ValueError("All rows of matrix_a must have the same number of columns.")
|
||||
|
||||
n_rows_b = len(matrix_b)
|
||||
|
||||
if n_cols_a != n_rows_b:
|
||||
raise ValueError(
|
||||
f"Matrix dimension mismatch: matrix_a columns {n_cols_a} != matrix_b rows {n_rows_b}"
|
||||
)
|
||||
|
||||
n_cols_b = len(matrix_b[0])
|
||||
|
||||
if any(len(row) != n_cols_b for row in matrix_b):
|
||||
raise ValueError("All rows of matrix_b must have the same number of columns.")
|
||||
|
||||
result: List[List[float]] = []
|
||||
for i in range(len(matrix_a)):
|
||||
row: List[float] = []
|
||||
for j in range(n_cols_b):
|
||||
elem = sum(matrix_a[i][k] * matrix_b[k][j] for k in range(n_cols_a))
|
||||
row.append(elem)
|
||||
result.append(row)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def transpose(matrix: List[List[float]]) -> List[List[float]]:
|
||||
"""Return the transpose of a 2D matrix."""
|
||||
if not matrix:
|
||||
raise ValueError("Cannot transpose an empty matrix.")
|
||||
|
||||
n_rows = len(matrix)
|
||||
n_cols = len(matrix[0])
|
||||
|
||||
if any(len(row) != n_cols for row in matrix):
|
||||
raise ValueError("All rows of the matrix must have the same number of columns.")
|
||||
|
||||
return [[matrix[i][j] for i in range(n_rows)] for j in range(n_cols)]
|
||||
|
||||
|
||||
def rotate_clockwise(matrix: List[List[float]]) -> List[List[float]]:
|
||||
"""Rotate a square matrix 90 degrees clockwise."""
|
||||
if not matrix:
|
||||
raise ValueError("Cannot rotate an empty matrix.")
|
||||
|
||||
n_cols = len(matrix[0])
|
||||
if any(len(row) != n_cols for row in matrix):
|
||||
raise ValueError("All rows of the matrix must have the same number of columns.")
|
||||
|
||||
transposed = transpose(matrix)
|
||||
return [row[::-1] for row in transposed]
|
||||
|
||||
|
||||
def rot_2D(theta: float) -> List[List[float]]:
|
||||
"""Return the 2D rotation matrix for a given angle in degrees."""
|
||||
rad = math.radians(theta)
|
||||
c = math.cos(rad)
|
||||
s = math.sin(rad)
|
||||
return [[c, -s], [s, c]]
|
||||
|
||||
|
||||
def rot_3D(angle: float, axis: str) -> list[list[float]]:
|
||||
"""Erzeugt eine 3D-Rotationsmatrix um die angegebene Achse ('x', 'y' oder 'z')."""
|
||||
rad = math.radians(angle)
|
||||
c, s = math.cos(rad), math.sin(rad)
|
||||
|
||||
axis = axis.lower()
|
||||
if axis == 'x':
|
||||
return [
|
||||
[1.0, 0.0, 0.0],
|
||||
[0.0, c, -s],
|
||||
[0.0, s, c]
|
||||
]
|
||||
elif axis == 'y':
|
||||
return [
|
||||
[c, 0.0, s],
|
||||
[0.0, 1.0, 0.0],
|
||||
[-s, 0.0, c]
|
||||
]
|
||||
elif axis == 'z':
|
||||
return [
|
||||
[c, -s, 0.0],
|
||||
[s, c, 0.0],
|
||||
[0.0, 0.0, 1.0]
|
||||
]
|
||||
else:
|
||||
raise ValueError("Achse muss 'x', 'y' oder 'z' sein.")
|
||||
|
||||
|
||||
def project_ortho(point: tuple[float, float, float], scale: float = 1.0) -> tuple[float, float]:
|
||||
"""Projiziert einen 3D-Punkt orthogonal auf eine 2D-Ebene und skaliert ihn."""
|
||||
x, y, z = point
|
||||
return (x * scale, y * scale)
|
||||
|
||||
def project_perspective(point: tuple[float, float, float], distance: float = 200.0, scale: float = 1.0) -> tuple[float, float]:
|
||||
"""Projiziert einen 3D-Punkt perspektivisch auf eine 2D-Fläche."""
|
||||
x, y, z = point
|
||||
# Verhindert Division durch 0, falls z genau bei -distance liegt
|
||||
factor = distance / (distance + z) if (distance + z) != 0 else 1.0
|
||||
return (x * factor * scale, y * factor * scale)
|
||||
|
||||
if __name__ == "__main__":
|
||||
a = [[1, 2, 3], [4, 5, 6]]
|
||||
b = [[7, 8], [9, 10], [11, 12]]
|
||||
|
||||
print("matmul(a, b):", matmul(a, b))
|
||||
print("transpose(a):", transpose(a))
|
||||
|
||||
# Teste deine Tests mit: python -m pytest
|
||||
@@ -0,0 +1,104 @@
|
||||
import math
|
||||
import pygame
|
||||
from spiel.game import Game
|
||||
from spiel.compute import rot_3D, project_perspective
|
||||
|
||||
|
||||
class CubeGame(Game):
|
||||
"""Ein interaktives 3D-Würfel-Spiel basierend auf der MatrixMania-Basisklasse."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
super().__init__(
|
||||
title="MatrixMania - Rotierender Würfel",
|
||||
fps=60,
|
||||
size=(800, 600)
|
||||
)
|
||||
|
||||
# 8 Eckpunkte eines Würfels im 3D-Raum (x, y, z)
|
||||
self.vertices = [
|
||||
[-50, -50, -50],
|
||||
[50, -50, -50],
|
||||
[50, 50, -50],
|
||||
[-50, 50, -50],
|
||||
[-50, -50, 50],
|
||||
[50, -50, 50],
|
||||
[50, 50, 50],
|
||||
[-50, 50, 50]
|
||||
]
|
||||
|
||||
# Die 12 Kanten des Würfels (verbinden jeweils zwei Indizes)
|
||||
self.edges = [
|
||||
(0, 1), (1, 2), (2, 3), (3, 0), # Hinteres Quadrat
|
||||
(4, 5), (5, 6), (6, 7), (7, 4), # Vorderes Quadrat
|
||||
(0, 4), (1, 5), (2, 6), (3, 7) # Verbindungskanten
|
||||
]
|
||||
|
||||
self.angle_x = 0.0
|
||||
self.angle_y = 0.0
|
||||
|
||||
def handle_event(self, event: pygame.event.Event) -> bool:
|
||||
"""Verarbeitet Events (z. B. Schließen des Fensters oder ESC-Taste)."""
|
||||
if event.type == pygame.QUIT:
|
||||
return False
|
||||
if event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
|
||||
return False
|
||||
return True
|
||||
|
||||
def update_game(self) -> bool:
|
||||
"""Aktualisiert die Rotationswinkel bei jedem Frame."""
|
||||
self.angle_x += 1.0
|
||||
self.angle_y += 1.5
|
||||
return True
|
||||
|
||||
def draw_game(self) -> None:
|
||||
"""Zeichnet den 3D-Würfel auf den Bildschirm."""
|
||||
if self.screen is None:
|
||||
return
|
||||
|
||||
# Hintergrund füllen (dunkles Blau/Grau)
|
||||
self.screen.fill((20, 20, 30))
|
||||
|
||||
center_x = self.size[0] // 2
|
||||
center_y = self.size[1] // 2
|
||||
|
||||
projected_points = []
|
||||
|
||||
for vertex in self.vertices:
|
||||
# 1. Rotation um die X-Achse
|
||||
rx_mat = rot_3D(self.angle_x, 'x')
|
||||
v_rx = [
|
||||
rx_mat[0][0] * vertex[0] + rx_mat[0][1] * vertex[1] + rx_mat[0][2] * vertex[2],
|
||||
rx_mat[1][0] * vertex[0] + rx_mat[1][1] * vertex[1] + rx_mat[1][2] * vertex[2],
|
||||
rx_mat[2][0] * vertex[0] + rx_mat[2][1] * vertex[1] + rx_mat[2][2] * vertex[2]
|
||||
]
|
||||
|
||||
# 2. Rotation um die Y-Achse
|
||||
ry_mat = rot_3D(self.angle_y, 'y')
|
||||
v_rot = [
|
||||
ry_mat[0][0] * v_rx[0] + ry_mat[0][1] * v_rx[1] + ry_mat[0][2] * v_rx[2],
|
||||
ry_mat[1][0] * v_rx[0] + ry_mat[1][1] * v_rx[1] + ry_mat[1][2] * v_rx[2],
|
||||
ry_mat[2][0] * v_rx[0] + ry_mat[2][1] * v_rx[1] + ry_mat[2][2] * v_rx[2]
|
||||
]
|
||||
|
||||
# 3. Perspektivische Projektion (z + 300, damit der Würfel vor der Kamera liegt)
|
||||
proj_x, proj_y = project_perspective(
|
||||
(v_rot[0], v_rot[1], v_rot[2] + 300),
|
||||
distance=300.0,
|
||||
scale=1.5
|
||||
)
|
||||
|
||||
# In Bildschirmkoordinaten umrechnen (Zentrum als Ursprung)
|
||||
projected_points.append((center_x + proj_x, center_y + proj_y))
|
||||
|
||||
# Kanten des Würfels zeichnen (Neon-Türkis)
|
||||
for edge in self.edges:
|
||||
p1 = projected_points[edge[0]]
|
||||
p2 = projected_points[edge[1]]
|
||||
pygame.draw.line(self.screen, (0, 255, 180), p1, p2, 2)
|
||||
|
||||
# Eckpunkte als weiße Kreise zeichnen
|
||||
for p in projected_points:
|
||||
pygame.draw.circle(self.screen, (255, 255, 255), (int(p[0]), int(p[1])), 4)
|
||||
|
||||
# Aufruf der Basisklasse, um das Display zu aktualisieren (flip)
|
||||
super().draw_game()
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Basisklasse ``Game`` für einfache pygame-Anwendungen."""
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
class Game:
|
||||
"""Basisklasse für pygame-Spiele.
|
||||
|
||||
Unterklassen passen das Verhalten durch Überschreiben von
|
||||
:meth:`handle_event`, :meth:`update_game` und :meth:`draw_game` an.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
title: str,
|
||||
fps: int = 60,
|
||||
size: tuple[int, int] = (640, 400),
|
||||
) -> None:
|
||||
"""Legt Fenstertitel, Bildrate und Fenstergröße fest.
|
||||
|
||||
Args:
|
||||
title: Titel des Fensters.
|
||||
fps: Maximale Bilder pro Sekunde.
|
||||
size: Fenstergröße als (Breite, Höhe) in Pixeln.
|
||||
"""
|
||||
self.title: str = title
|
||||
self.fps: int = fps
|
||||
self.size: tuple[int, int] = size
|
||||
self.clock: pygame.time.Clock = pygame.time.Clock()
|
||||
self.dt: float = 0
|
||||
self.screen: pygame.Surface | None = None
|
||||
|
||||
def init_game(self) -> None:
|
||||
"""Initialisiert pygame und erzeugt das Fenster."""
|
||||
pygame.init()
|
||||
pygame.display.set_caption(self.title)
|
||||
self.screen = pygame.display.set_mode(self.size)
|
||||
|
||||
def game_loop(self) -> None:
|
||||
"""Führt die Hauptschleife aus, bis Events oder Update ``False`` liefern."""
|
||||
while True:
|
||||
# Berechnung der Zeitdifferenz seit dem letzten Frame
|
||||
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) -> None:
|
||||
"""Beendet pygame."""
|
||||
pygame.quit()
|
||||
|
||||
def event_handling(self) -> bool:
|
||||
"""Verteilt alle anstehenden Events an :meth:`handle_event`.
|
||||
|
||||
Bleibt in der Unterklasse unverändert.
|
||||
|
||||
Returns:
|
||||
``False``, sobald ein Event das Spiel beenden soll, sonst ``True``.
|
||||
"""
|
||||
for event in pygame.event.get():
|
||||
if not self.handle_event(event):
|
||||
return False
|
||||
return True
|
||||
|
||||
def handle_event(self, event: pygame.event.Event) -> bool:
|
||||
"""Verarbeitet ein einzelnes Event.
|
||||
|
||||
Wird in der Unterklasse überschrieben.
|
||||
|
||||
Args:
|
||||
event: Das zu verarbeitende pygame-Event.
|
||||
|
||||
Returns:
|
||||
``False`` bei ``pygame.QUIT``, sonst ``True``.
|
||||
"""
|
||||
if event.type == pygame.QUIT:
|
||||
return False
|
||||
return True
|
||||
|
||||
def update_game(self) -> bool:
|
||||
"""Aktualisiert den Spielzustand um einen Frame.
|
||||
|
||||
Returns:
|
||||
``False``, wenn das Spiel beendet werden soll, sonst ``True``.
|
||||
"""
|
||||
return True
|
||||
|
||||
def draw_game(self) -> None:
|
||||
"""Zeichnet den aktuellen Frame und bringt ihn zur Anzeige."""
|
||||
pygame.display.flip()
|
||||
|
||||
def run(self) -> None:
|
||||
"""Startet das Spiel: Initialisierung, Hauptschleife, Beenden."""
|
||||
self.init_game()
|
||||
self.game_loop()
|
||||
self.exit_game()
|
||||
Reference in new issue
Block a user