Rotierender Würfel mit CubeGame
This commit is contained in:
commit
8300228059
17 files changed
+551
No files matched your search
Whitespace-only changes.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -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.")
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user