in cube_game, Klasse CubeGame Programmiert

This commit is contained in:
taraseidler committed 2026-10-28 17:14:12 +01:00
1 parent d4da7cfd37
commit 2d3df3e5de
1 file changed
+70
+70
View File
@@ -0,0 +1,70 @@
"""A rotating wireframe cube rendered with pygame."""
from __future__ import annotations
from typing import List, Tuple
import pygame
from compute import matmul, project_ortho, rot_3D
from game import Game
# Cube vertices (corner points) of a cube with edge length 2.
VERTICES: List[List[float]] = [
[-1.0, -1.0, -1.0], [ 1.0, -1.0, -1.0],
[ 1.0, 1.0, -1.0], [-1.0, 1.0, -1.0],
[-1.0, -1.0, 1.0], [ 1.0, -1.0, 1.0],
[ 1.0, 1.0, 1.0], [-1.0, 1.0, 1.0],
]
EDGES: List[Tuple[int, int]] = [
(0, 1), (1, 2), (2, 3), (3, 0), # back face
(4, 5), (5, 6), (6, 7), (7, 4), # front face
(0, 4), (1, 5), (2, 6), (3, 7), # connecting edges
]
WHITE = (255, 255, 255)
SPEED = 0.01 # rotation per frame in radians
SCALE = 100 # pixels per world unit
class CubeGame(Game):
"""Rotates a wireframe cube continuously around two axes."""
def __init__(self, title: str = "Wuerfel") -> None:
"""Store the initial rotation angles."""
super().__init__(title=title)
self.angle_x = 0.0
self.angle_y = 0.0
def update_game(self) -> bool:
"""Advance both rotation angles by one step."""
self.angle_x += SPEED
self.angle_y += 0.5 * SPEED
return True
def rotated_vertices(self) -> List[Tuple[float, float]]:
"""Rotate all vertices and project them onto the screen."""
rotation = matmul(rot_3D(self.angle_x, "x"),
rot_3D(self.angle_y, "y"))
projected: List[Tuple[float, float]] = []
for vertex in VERTICES:
column = [[vertex[0]], [vertex[1]], [vertex[2]]]
rotated = matmul(rotation, column)
point = (rotated[0][0], rotated[1][0], rotated[2][0])
x, y = project_ortho(point, SCALE)
projected.append(self.absolut((x, y)))
return projected
def draw_game(self) -> None:
"""Draw the projected cube edges."""
self.clear()
vertices = self.rotated_vertices()
for start, end in EDGES:
pygame.draw.line(self.screen, WHITE,
vertices[start], vertices[end], 2)
self.display()
if __name__ == "__main__":
CubeGame().start()