from __future__ import annotations import pygame from game.game import Game # Standard matrix type definition Matrix = list[list[float]] class CubeGame(Game): """3‑D cube demo. The cube is stored as a list of eight vertex coordinates. On each frame it is rotated around its centre and the projected 2‑D coordinates are drawn using ``pygame.draw.line``. """ def __init__(self) -> None: super().__init__("Cube Game") self.centre: list[float] = [0.0, 0.0, 0.0] self.corners: Matrix = [ [-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], ] self.rotation: dict[str, float] = {"x": 0.0, "y": 0.0, "z": 0.0} self.focal: float = 300.0 self.distance: float = 5.0 self.edges: list[tuple[int, int]] = [ (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.rotated_corners: Matrix | None = None self.hold_keys: set[int] = set() def update_game(self) -> bool: for key in self.hold_keys: if key == pygame.K_UP: self.rotation["x"] += 1 elif key == pygame.K_DOWN: self.rotation["x"] -= 1 elif key == pygame.K_LEFT: self.rotation["y"] -= 1 elif key == pygame.K_RIGHT: self.rotation["y"] += 1 # Apply rotations to vertices each frame from game.compute import rot_3d points: Matrix = [c[:] for c in self.corners] for axis in ("x", "y", "z"): points = rot_3d(points, self.rotation[axis], axis) self.rotated_corners = points return True def draw_game(self) -> None: if self.screen is None: return self.screen.fill((0, 0, 0)) w, h = self.size cx, cy = w // 2, h // 2 if self.rotated_corners is None: return def project(p: list[float]) -> tuple[int, int]: denom: float = p[2] + self.distance if denom == 0.0: denom = 0.0001 x: float = self.focal * p[0] / denom y: float = self.focal * p[1] / denom return cx + int(x), cy + int(y) for a_idx, b_idx in self.edges: a = project(self.rotated_corners[a_idx]) b = project(self.rotated_corners[b_idx]) pygame.draw.line(self.screen, (255, 255, 255), a, b, 2) pygame.display.flip() def handle_event(self, event: pygame.event.Event) -> bool: if event.type == pygame.KEYDOWN: self.hold_keys.add(event.key) elif event.type == pygame.KEYUP: self.hold_keys.discard(event.key) return True