84 lines
2.5 KiB
Python
84 lines
2.5 KiB
Python
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
|
||
|
||
def update_game(self) -> bool:
|
||
"""Rotate cube each frame and prepare projected coordinates.
|
||
|
||
Returns ``True`` to continue the main loop.
|
||
"""
|
||
self.rotation["y"] += 1.0
|
||
if self.rotation["y"] >= 360.0:
|
||
self.rotation["y"] -= 360.0
|
||
|
||
from game.compute import rot_3d
|
||
|
||
# Clone original vertices and apply rotations
|
||
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()
|
||
|