47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
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() |