In the Beginning there was
the Cube
This commit is contained in:
commit
442cb227cb
13 files changed
+578
No files matched your search
@@ -0,0 +1,164 @@
|
||||
import math
|
||||
|
||||
from tabulate import tabulate
|
||||
|
||||
|
||||
def matmul(matrix_a:list[list[float]], matrix_b: list[list[float]]) -> list[list[float]]:
|
||||
"""
|
||||
Add two numbers together.
|
||||
:param matrix_a: The first Matrix
|
||||
:type matrix_a: list[list[float]]
|
||||
:param matrix_b: The second Matrix
|
||||
:type matrix_b: list[list[float]]
|
||||
:return: The Matrix Multiplication of matrix_a and matrix_b
|
||||
:rtype: list[list[float]]
|
||||
"""
|
||||
try:
|
||||
if len(matrix_a[0]) != len(matrix_b):
|
||||
raise ValueError("Differing Matrix Size")
|
||||
target_height = len(matrix_a)
|
||||
target_width = len(matrix_b[0])
|
||||
|
||||
end_matrix : list[list[float]]= []
|
||||
|
||||
|
||||
for height in range(target_height):
|
||||
end_matrix.append([])
|
||||
for width in range(target_width):
|
||||
row = matrix_a[height]
|
||||
column_ = []
|
||||
for b in matrix_b:
|
||||
column_.append(b[width])
|
||||
result_quarter = 0
|
||||
for i in range(len(row)):
|
||||
result_quarter += row[i] * column_[i]
|
||||
end_matrix[height].append(float(result_quarter))
|
||||
|
||||
return end_matrix
|
||||
except ValueError:
|
||||
print("An Error has occurred")
|
||||
except IndexError:
|
||||
print("Tried to call non-existing Index")
|
||||
except TypeError:
|
||||
print("Tried to insert not a Number")
|
||||
|
||||
|
||||
|
||||
def transpose(matrix:list[list[float]]) -> list[list[float]]:
|
||||
"""
|
||||
Transposes a matrix.
|
||||
:param matrix: The Matrix, that will be transposed
|
||||
:type matrix: list[list[float]]
|
||||
:return: The transposed matrix
|
||||
:rtype: list[list[float]]
|
||||
"""
|
||||
|
||||
transposed_matrix = []
|
||||
for x in range(len(matrix[0])):
|
||||
column = []
|
||||
for b in matrix:
|
||||
column.append(b[x])
|
||||
transposed_matrix.append(column)
|
||||
|
||||
return transposed_matrix
|
||||
|
||||
def rot_2d(angle:float) -> list[list[float]]:
|
||||
"""
|
||||
Creates a Rotation Matrix out of the given angle
|
||||
:param angle: The rotation in radians
|
||||
:type angle: float
|
||||
:return: The Rotation Matrix
|
||||
:rtype: list[list[float]]
|
||||
"""
|
||||
sin = round(math.sin(angle), 4)
|
||||
cos = round(math.cos(angle), 4)
|
||||
return [[cos, -sin],
|
||||
[sin, cos]]
|
||||
|
||||
def rot_3d(angle: float, axis: str) -> list[list[float]]:
|
||||
"""
|
||||
Creates a 3D Rotation Matrix out of the given angle and axis
|
||||
:param angle: The rotation in radians
|
||||
:type angle: float
|
||||
:param axis: The Axis on which it rotates; only "x", "y" or "z"
|
||||
:type axis: str
|
||||
:return: The 3D Rotation Matrix
|
||||
:rtype: list[list[float]]
|
||||
"""
|
||||
axis = axis.lower()
|
||||
sin = round(math.sin(angle), 4)
|
||||
cos = round(math.cos(angle), 4)
|
||||
if axis == "x":
|
||||
return[[1, 0, 0],
|
||||
[0, cos, -sin],
|
||||
[0, sin, cos]]
|
||||
if axis == "y":
|
||||
return[[cos, 0, sin],
|
||||
[0, 1, 0],
|
||||
[-sin, 0, cos]]
|
||||
if axis == "z":
|
||||
return [[cos, -sin, 0],
|
||||
[sin, cos, 0],
|
||||
[0, 0, 1]]
|
||||
|
||||
raise ValueError
|
||||
|
||||
# For Both below add the Doc String!
|
||||
def project_ortho(point: tuple[float, float, float], scale: float = 1) -> tuple[float, float]:
|
||||
"""
|
||||
Projects a 3D Position into an orthogonal 2D View
|
||||
:param point: The 3D Point
|
||||
:type point: tuple[float, float, float]
|
||||
:param scale: The scale by which the point gets scaled; regular is 1.0
|
||||
:type scale: float
|
||||
:return: The 3D Point on a 2D plane
|
||||
:rtype: tuple[float, float]
|
||||
"""
|
||||
return (point[0] * scale,
|
||||
point[1] * scale)
|
||||
|
||||
def project_perspective(point: tuple[float, float, float], focal_length: float = 1.0,
|
||||
scale: float = 1.0, camera_distance: float = 4.0) -> tuple[float, float]:
|
||||
"""
|
||||
Projects a 3D Position into a perspective 2D View
|
||||
:param point: The 3D Point
|
||||
:type point: tuple[float, float, float]
|
||||
:param focal_length: strength of perspective; regular is 1.0
|
||||
:type focal_length: float
|
||||
:param scale: The scale by which the point gets scaled; regular is 1.0
|
||||
:type scale: float
|
||||
:param camera_distance: How far the Camera is away from the point; regular is 4.0
|
||||
:return: The 3D Point on a 2D plane
|
||||
:rtype: tuple[float, float]
|
||||
"""
|
||||
return (point[0] * focal_length * scale / (point[2] + camera_distance),
|
||||
point[1] * focal_length * scale / (point[2] + camera_distance), )
|
||||
|
||||
|
||||
def print_matrix(matrix:list[list[float]]) -> None:
|
||||
for row in matrix:
|
||||
print(row)
|
||||
|
||||
if __name__ == "__main__":
|
||||
matrix_bsp_a = [[1, 2, 3], [4, 5, 6]]
|
||||
matrix_bsp_b = [[1, 2], [3, 4], [5, 6]]
|
||||
matrix_bsp_c = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
|
||||
matrix_bsp_d = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
|
||||
|
||||
if False:
|
||||
matrix_bsp_result = matmul(matrix_bsp_c, matrix_bsp_d)
|
||||
print_matrix(matrix_bsp_result)
|
||||
|
||||
if False:
|
||||
matrix_bsp_result = transpose(matrix_bsp_d)
|
||||
#print_matrix(matrix_bsp_c)
|
||||
print_matrix(matrix_bsp_result)
|
||||
|
||||
if True:
|
||||
#print_matrix(rot_2d(math.pi*.25))
|
||||
print(tabulate(rot_2d(1.33)))
|
||||
|
||||
|
||||
# Test Kommenter
|
||||
|
||||
print("Done")
|
||||
@@ -0,0 +1,103 @@
|
||||
import pygame
|
||||
from game import Game
|
||||
import compute
|
||||
|
||||
BLACK = (0, 0, 0)
|
||||
GREEN = (0, 255, 0)
|
||||
RED = (255, 0, 0)
|
||||
|
||||
class CubeGame(Game):
|
||||
"""Der Mond kreist um die Erde."""
|
||||
def __init__(self,title: str = "Cube: The Game", fps: int = 60, size: tuple[int, int] = (1280, 800),) -> None:
|
||||
"""Legt Startposition, Drehwinkel und Rotationsmatrix fest."""
|
||||
super().__init__(title, fps, size)
|
||||
|
||||
self.cube_corner_points = [(-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.cube_edges = [(0, 1), (0, 3), (0, 4),
|
||||
(6, 2), (6, 7), (6, 5),
|
||||
(1, 2), (1, 5),
|
||||
(3, 7), (3, 2),
|
||||
(4, 5), (4, 7)]
|
||||
|
||||
self.screen_middle = (self.size[0]// 2, self.size[1] // 2)
|
||||
|
||||
self.spin = .05
|
||||
self.camera_scale_ortho = 150
|
||||
self.camera_scale_project = 400
|
||||
self.orthogonal = False
|
||||
self.direction = (0, 0)
|
||||
|
||||
|
||||
def handle_event(self, event):
|
||||
if not super().handle_event(event):
|
||||
return False
|
||||
if event.type == pygame.KEYDOWN:
|
||||
print(self.direction)
|
||||
if event.key == pygame.K_UP:
|
||||
self.direction = (max(-1, self.direction[0] - .1), self.direction[1])
|
||||
if event.key == pygame.K_DOWN:
|
||||
self.direction = (min(1, self.direction[0] + .1), self.direction[1])
|
||||
if event.key == pygame.K_RIGHT:
|
||||
self.direction = (self.direction[0], max(-1, self.direction[1] - .1))
|
||||
if event.key == pygame.K_LEFT:
|
||||
self.direction = ( self.direction[0], min(1, self.direction[1] + .1))
|
||||
if event.key == pygame.K_SPACE:
|
||||
self.orthogonal = not self.orthogonal
|
||||
return True
|
||||
|
||||
def rotate(self, axis, dir=1):
|
||||
for point in range(len(self.cube_corner_points)):
|
||||
point_matrix = [[self.cube_corner_points[point][0]],
|
||||
[self.cube_corner_points[point][1]],
|
||||
[self.cube_corner_points[point][2]]]
|
||||
point_temp = compute.matmul(compute.rot_3d(self.spin*dir, axis), point_matrix)
|
||||
self.cube_corner_points[point] = (point_temp[0][0], point_temp[1][0], point_temp[2][0])
|
||||
|
||||
def update_game(self) -> bool:
|
||||
"""Dreht den Mond ein Stück weiter."""
|
||||
if self.direction[0] != 0:
|
||||
self.rotate("x", self.direction[0])
|
||||
if self.direction[1] != 0:
|
||||
self.rotate("y", self.direction[1])
|
||||
self.direction = (round(self.direction[0], 4), round(self.direction[1], 4))
|
||||
|
||||
return True
|
||||
|
||||
def draw_game(self) -> None:
|
||||
"""Zeichnet Erde und Mond."""
|
||||
self.screen.fill(BLACK)
|
||||
|
||||
for edge in self.cube_edges:
|
||||
point2d_a = self.to_middle(self.perspective(self.cube_corner_points[edge[0]]))
|
||||
point2d_b = self.to_middle(self.perspective(self.cube_corner_points[edge[1]]))
|
||||
pygame.draw.line(self.screen, RED, point2d_a, point2d_b)
|
||||
|
||||
for point in self.cube_corner_points:
|
||||
point2d = self.to_middle(self.perspective(point))
|
||||
pygame.draw.circle(self.screen, GREEN, point2d, 5)
|
||||
|
||||
|
||||
pygame.display.flip()
|
||||
|
||||
def perspective(self, point):
|
||||
if self.orthogonal:
|
||||
return self.orthogonal_perspective(point)
|
||||
return self.project_perspective(point)
|
||||
|
||||
def orthogonal_perspective(self, point):
|
||||
return compute.project_ortho(point, scale=self.camera_scale_ortho)
|
||||
|
||||
def project_perspective(self, point):
|
||||
return compute.project_perspective(point, scale=self.camera_scale_project)
|
||||
|
||||
def to_middle(self, point):
|
||||
return point[0] + self.screen_middle[0], point[1] + self.screen_middle[1]
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
cube = CubeGame()
|
||||
cube.run()
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Basisklasse ``Game`` für einfache pygame-Anwendungen."""
|
||||
|
||||
import pygame
|
||||
|
||||
|
||||
class Game:
|
||||
"""Basisklasse für pygame-Spiele.
|
||||
|
||||
Unterklassen passen das Verhalten durch Überschreiben von
|
||||
:meth:`handle_event`, :meth:`update_game` und :meth:`draw_game` an.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
title: str,
|
||||
fps: int = 60,
|
||||
size: tuple[int, int] = (640, 400),
|
||||
) -> None:
|
||||
"""Legt Fenstertitel, Bildrate und Fenstergröße fest.
|
||||
|
||||
Args:
|
||||
title: Titel des Fensters.
|
||||
fps: Maximale Bilder pro Sekunde.
|
||||
size: Fenstergröße als (Breite, Höhe) in Pixeln.
|
||||
"""
|
||||
self.title: str = title
|
||||
self.fps: int = fps
|
||||
self.size: tuple[int, int] = size
|
||||
self.clock: pygame.time.Clock = pygame.time.Clock()
|
||||
self.dt: float = 0
|
||||
self.screen: pygame.Surface | None = None
|
||||
|
||||
def init_game(self) -> None:
|
||||
"""Initialisiert pygame und erzeugt das Fenster."""
|
||||
pygame.init()
|
||||
pygame.display.set_caption(self.title)
|
||||
self.screen = pygame.display.set_mode(self.size)
|
||||
|
||||
def game_loop(self) -> None:
|
||||
"""Führt die Hauptschleife aus, bis Events oder Update ``False`` liefern."""
|
||||
while True:
|
||||
# Berechnung der Zeitdifferenz seit dem letzten Frame
|
||||
self.dt = self.clock.tick(self.fps) / 1000
|
||||
if self.event_handling() == False:
|
||||
break
|
||||
if self.update_game() == False:
|
||||
break
|
||||
self.draw_game()
|
||||
|
||||
def exit_game(self) -> None:
|
||||
"""Beendet pygame."""
|
||||
pygame.quit()
|
||||
|
||||
def event_handling(self) -> bool:
|
||||
"""Verteilt alle anstehenden Events an :meth:`handle_event`.
|
||||
|
||||
Bleibt in der Unterklasse unverändert.
|
||||
|
||||
Returns:
|
||||
``False``, sobald ein Event das Spiel beenden soll, sonst ``True``.
|
||||
"""
|
||||
for event in pygame.event.get():
|
||||
if not self.handle_event(event):
|
||||
return False
|
||||
return True
|
||||
|
||||
def handle_event(self, event: pygame.event.Event) -> bool:
|
||||
"""Verarbeitet ein einzelnes Event.
|
||||
|
||||
Wird in der Unterklasse überschrieben.
|
||||
|
||||
Args:
|
||||
event: Das zu verarbeitende pygame-Event.
|
||||
|
||||
Returns:
|
||||
``False`` bei ``pygame.QUIT``, sonst ``True``.
|
||||
"""
|
||||
if event.type == pygame.QUIT:
|
||||
return False
|
||||
return True
|
||||
|
||||
def update_game(self) -> bool:
|
||||
"""Aktualisiert den Spielzustand um einen Frame.
|
||||
|
||||
Returns:
|
||||
``False``, wenn das Spiel beendet werden soll, sonst ``True``.
|
||||
"""
|
||||
return True
|
||||
|
||||
def draw_game(self) -> None:
|
||||
"""Zeichnet den aktuellen Frame und bringt ihn zur Anzeige."""
|
||||
pygame.display.flip()
|
||||
|
||||
def run(self) -> None:
|
||||
"""Startet das Spiel: Initialisierung, Hauptschleife, Beenden."""
|
||||
self.init_game()
|
||||
self.game_loop()
|
||||
self.exit_game()
|
||||
Reference in new issue
Block a user