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,3 @@
|
|||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
.env
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
# Default ignored files
|
||||||
|
/shelf/
|
||||||
|
/workspace.xml
|
||||||
|
# Editor-based HTTP Client requests
|
||||||
|
/httpRequests/
|
||||||
|
# Datasource local storage ignored files
|
||||||
|
/dataSources/
|
||||||
|
/dataSources.local.xml
|
||||||
Generated
+10
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<module type="PYTHON_MODULE" version="4">
|
||||||
|
<component name="NewModuleRootManager">
|
||||||
|
<content url="file://$MODULE_DIR$">
|
||||||
|
<excludeFolder url="file://$MODULE_DIR$/.venv" />
|
||||||
|
</content>
|
||||||
|
<orderEntry type="jdk" jdkName="Python 3.13 virtualenv at C:\Users\steph\Documents\Ohm\Media Engineering\Media Engineering SoSe26\Prog2A\.venv" jdkType="Python SDK" />
|
||||||
|
<orderEntry type="sourceFolder" forTests="false" />
|
||||||
|
</component>
|
||||||
|
</module>
|
||||||
+12
@@ -0,0 +1,12 @@
|
|||||||
|
<component name="InspectionProjectProfileManager">
|
||||||
|
<profile version="1.0">
|
||||||
|
<option name="myName" value="Project Default" />
|
||||||
|
<inspection_tool class="PyPep8Inspection" enabled="true" level="INFORMATION" enabled_by_default="true">
|
||||||
|
<option name="ignoredErrors">
|
||||||
|
<list>
|
||||||
|
<option value="W292" />
|
||||||
|
</list>
|
||||||
|
</option>
|
||||||
|
</inspection_tool>
|
||||||
|
</profile>
|
||||||
|
</component>
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<component name="InspectionProjectProfileManager">
|
||||||
|
<settings>
|
||||||
|
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||||
|
<version value="1.0" />
|
||||||
|
</settings>
|
||||||
|
</component>
|
||||||
Generated
+7
@@ -0,0 +1,7 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="Black">
|
||||||
|
<option name="sdkName" value="Python 3.14 (Wuerfel)" />
|
||||||
|
</component>
|
||||||
|
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.13 virtualenv at C:\Users\steph\Documents\Ohm\Media Engineering\Media Engineering SoSe26\Prog2A\.venv" project-jdk-type="Python SDK" />
|
||||||
|
</project>
|
||||||
Generated
+8
@@ -0,0 +1,8 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="ProjectModuleManager">
|
||||||
|
<modules>
|
||||||
|
<module fileurl="file://$PROJECT_DIR$/.idea/Wuerfel.iml" filepath="$PROJECT_DIR$/.idea/Wuerfel.iml" />
|
||||||
|
</modules>
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
Generated
+6
@@ -0,0 +1,6 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project version="4">
|
||||||
|
<component name="VcsDirectoryMappings">
|
||||||
|
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||||
|
</component>
|
||||||
|
</project>
|
||||||
@@ -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()
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Installiert die Abhängigkeiten aus pyproject.toml in die aktuelle Python-Umgebung.
|
||||||
|
|
||||||
|
Ersatz für "Install requirements" aus PyCharm, wenn das Projekt eine pyproject.toml
|
||||||
|
statt einer requirements.txt hat. Kein Build, keine besondere Projektstruktur nötig,
|
||||||
|
nur Standardbibliothek (Python >= 3.11).
|
||||||
|
|
||||||
|
Benutzung:
|
||||||
|
In PyCharm: Rechtsklick auf diese Datei -> Run 'install_dependencies'
|
||||||
|
Im Terminal (venv aktiv): python install_dependencies.py
|
||||||
|
|
||||||
|
Ohne Parameter wird ALLES installiert:
|
||||||
|
[project].dependencies + alle [project.optional-dependencies] + alle [dependency-groups]
|
||||||
|
|
||||||
|
Abweichendes Verhalten:
|
||||||
|
python install_dependencies.py --extra dev nur Basis + Extra "dev"
|
||||||
|
python install_dependencies.py --group test nur Basis + Gruppe "test"
|
||||||
|
python install_dependencies.py --no-main --group dev
|
||||||
|
python install_dependencies.py --list nur anzeigen, nichts installieren
|
||||||
|
python install_dependencies.py --write requirements.txt schreiben statt installieren
|
||||||
|
python install_dependencies.py --write -o reqs.txt
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
if sys.version_info < (3, 11):
|
||||||
|
sys.exit("Dieses Skript braucht Python 3.11 oder neuer (tomllib). "
|
||||||
|
f"Aktuell: {sys.version.split()[0]}")
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import tomllib
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
PROJECT_DIR = Path(__file__).resolve().parent
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_group(groups: dict, name: str, seen: set[str] | None = None) -> list[str]:
|
||||||
|
"""Löst eine Dependency-Group inkl. {include-group = "..."} rekursiv auf."""
|
||||||
|
seen = set() if seen is None else seen
|
||||||
|
if name in seen:
|
||||||
|
raise ValueError(f"Zyklische include-group: {name}")
|
||||||
|
if name not in groups:
|
||||||
|
raise KeyError(f"Dependency-Group '{name}' nicht gefunden")
|
||||||
|
seen.add(name)
|
||||||
|
result: list[str] = []
|
||||||
|
for entry in groups[name]:
|
||||||
|
if isinstance(entry, str):
|
||||||
|
result.append(entry)
|
||||||
|
elif isinstance(entry, dict) and "include-group" in entry:
|
||||||
|
result.extend(resolve_group(groups, entry["include-group"], seen))
|
||||||
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
def collect(data: dict, extras: list[str], groups: list[str], no_main: bool) -> list[str]:
|
||||||
|
project = data.get("project", {})
|
||||||
|
optional = project.get("optional-dependencies", {})
|
||||||
|
dep_groups = data.get("dependency-groups", {})
|
||||||
|
deps: list[str] = []
|
||||||
|
|
||||||
|
if not no_main:
|
||||||
|
deps.extend(project.get("dependencies", []))
|
||||||
|
for extra in extras:
|
||||||
|
if extra not in optional:
|
||||||
|
raise KeyError(f"Optional-Dependency '{extra}' nicht gefunden")
|
||||||
|
deps.extend(optional[extra])
|
||||||
|
for group in groups:
|
||||||
|
deps.extend(resolve_group(dep_groups, group))
|
||||||
|
|
||||||
|
# Duplikate entfernen, Reihenfolge behalten
|
||||||
|
return list(dict.fromkeys(d.strip() for d in deps if d.strip()))
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||||
|
p.add_argument("-p", "--pyproject", type=Path, default=PROJECT_DIR / "pyproject.toml",
|
||||||
|
help="Pfad zur pyproject.toml (Standard: neben diesem Skript)")
|
||||||
|
p.add_argument("--extra", action="append", default=None,
|
||||||
|
help="nur diese optional-dependencies (mehrfach möglich)")
|
||||||
|
p.add_argument("--group", action="append", default=None,
|
||||||
|
help="nur diese dependency-groups (mehrfach möglich)")
|
||||||
|
p.add_argument("--no-main", action="store_true", help="[project].dependencies weglassen")
|
||||||
|
p.add_argument("--list", action="store_true", help="Abhängigkeiten nur anzeigen")
|
||||||
|
p.add_argument("--write", action="store_true", help="requirements-Datei schreiben statt installieren")
|
||||||
|
p.add_argument("-o", "--output", type=Path, default=PROJECT_DIR / "requirements.txt",
|
||||||
|
help="Zieldatei für --write")
|
||||||
|
args = p.parse_args()
|
||||||
|
|
||||||
|
if not args.pyproject.exists():
|
||||||
|
print(f"{args.pyproject} nicht gefunden", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
data = tomllib.loads(args.pyproject.read_text(encoding="utf-8"))
|
||||||
|
all_extras = list(data.get("project", {}).get("optional-dependencies", {}))
|
||||||
|
all_groups = list(data.get("dependency-groups", {}))
|
||||||
|
|
||||||
|
# Ohne --extra/--group: alles. Mit einem davon: nur das Gewählte.
|
||||||
|
selective = args.extra is not None or args.group is not None
|
||||||
|
extras = (args.extra or []) if selective else all_extras
|
||||||
|
groups = (args.group or []) if selective else all_groups
|
||||||
|
|
||||||
|
try:
|
||||||
|
deps = collect(data, extras, groups, args.no_main)
|
||||||
|
except (KeyError, ValueError) as e:
|
||||||
|
print(f"Fehler: {e.args[0]}", file=sys.stderr)
|
||||||
|
print(f" Vorhandene --extra: {', '.join(all_extras) or '(keine)'}", file=sys.stderr)
|
||||||
|
print(f" Vorhandene --group: {', '.join(all_groups) or '(keine)'}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
parts = ([] if args.no_main else ["Basis"]) + [f"extra:{e}" for e in extras] + [f"group:{g}" for g in groups]
|
||||||
|
print(f"Auswahl: {', '.join(parts) or '(nichts)'}")
|
||||||
|
|
||||||
|
if args.list:
|
||||||
|
print("\n".join(deps) or "(keine Abhängigkeiten)")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
content = f"# Automatisch erzeugt aus {args.pyproject.name} – nicht von Hand bearbeiten\n" + "\n".join(deps) + "\n"
|
||||||
|
|
||||||
|
if args.write:
|
||||||
|
args.output.write_text(content, encoding="utf-8")
|
||||||
|
print(f"{len(deps)} Abhängigkeiten -> {args.output}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if not deps:
|
||||||
|
print("Keine Abhängigkeiten gefunden – nichts zu tun.")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
if sys.prefix == sys.base_prefix:
|
||||||
|
print("WARNUNG: Es ist kein virtuelles Environment aktiv – es wird in die globale "
|
||||||
|
f"Python-Installation installiert:\n {sys.prefix}", file=sys.stderr)
|
||||||
|
if sys.stdin.isatty() and input("Trotzdem fortfahren? [j/N] ").strip().lower() not in ("j", "ja", "y", "yes"):
|
||||||
|
return 1
|
||||||
|
|
||||||
|
with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False, encoding="utf-8") as tmp:
|
||||||
|
tmp.write(content)
|
||||||
|
tmp_path = Path(tmp.name)
|
||||||
|
try:
|
||||||
|
print(f"Installiere {len(deps)} Abhängigkeiten in {sys.prefix}\n")
|
||||||
|
return subprocess.call([sys.executable, "-m", "pip", "install", "-r", str(tmp_path)])
|
||||||
|
finally:
|
||||||
|
tmp_path.unlink(missing_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
[project]
|
||||||
|
name = "Wuerfel"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = ["tabulate", "ruff"]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = ["pytest", "ruff", "pytest-cov", "pygame"]
|
||||||
Reference in new issue
Block a user