import pygame from typing import List, Tuple from spiel.game import Game from spiel.compute import rot_3D, matmul, 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: """Rotate and project all corners each frame.""" # 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 handle_event(self, event) -> None: """Handle pygame events to rotate the cube with arrow keys.""" if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: self.angle_y -= 0.1 elif event.key == pygame.K_RIGHT: self.angle_y += 0.1 elif event.key == pygame.K_UP: self.angle_x -= 0.1 elif event.key == pygame.K_DOWN: self.angle_x += 0.1 def draw_game(self) -> None: """Render all edges as green lines.""" 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)