Code: Alles auswählen
import random
import time
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QGraphicsView, QGraphicsScene
from PyQt5.QtGui import QPainterPath
points = []
SPEED = 5000
MIN_DISTANCE = 30000
DISTANCE_VARIANCE = 20000
class Star:
D = 1000 # Durchmesser?
def __init__(self, scene):
path = QPainterPath()
path.addRect(-10, -10, 20, 20)
self._x, self._y = random.random() * 20000 - 10000, random.random() * 20000 - 10000
self._z = random.random() * 20000 + MIN_DISTANCE
self._speed = random.random() * SPEED
self._path = scene.addPath(path)
self._path.setPen(QtCore.Qt.red)
self.update(0) # force placement
def update(self, elapsed):
self._z -= elapsed * self._speed # z-Koordinate neu berechnen
if self._z < 0:
self._z = random.random() * DISTANCE_VARIANCE + MIN_DISTANCE # Zufallszahl * Multiplikator + Mindestabstand
self._path.setX(self._x * self.D / self._z) # ?
self._path.setY(self._y * self.D / self._z) # ?
self._path.setScale(1 - self._z / (MIN_DISTANCE + DISTANCE_VARIANCE)) # Sterne bei der Bewegung nach vorne größer skalieren
self._path.setRotation(self._path.rotation() + elapsed * 360) # Drehbewegung der Sterne
return False, []
class StarSpawner:
STARS_PER_SECOND = 10
TOTAL_STARS = 100
def __init__(self, scene):
self._star_spawn_period = 1.0 / self.STARS_PER_SECOND
self._accu = 0.0
self._count = self.TOTAL_STARS
self._scene = scene
def update(self, elapsed):
self._accu += elapsed
spawned_stars = []
while self._accu > self._star_spawn_period:
spawned_stars.append(Star(self._scene))
self._accu -= self._star_spawn_period
self._count -= len(spawned_stars)
return self._count <= 0, spawned_stars
class GraphicsWindow(QGraphicsView):
def __init__(self, parent=None):
super(GraphicsWindow, self).__init__(parent)
self._last = time.monotonic()
scene = QGraphicsScene(self)
self.setScene(scene) #
self._things = [StarSpawner(scene)]
scene.setSceneRect(-400, -400, 800, 800)
self.setCacheMode(QGraphicsView.CacheBackground)
self._timer = QtCore.QTimer(self)
self._timer.setSingleShot(False)
self._timer.setInterval(1000 / 60)
self._timer.timeout.connect(self._update_all)
self._timer.start()
def _update_all(self):
now = time.monotonic()
elapsed = now - self._last
self._last = now
to_remove = []
total_to_add = []
for thing in self._things:
remove, to_add = thing.update(elapsed)
if remove:
to_remove.append(thing)
total_to_add.extend(to_add)
self._things = total_to_add + \
[thing for thing in self._things if thing not in to_remove]
def main():
app = QApplication(sys.argv)
graphics_window = GraphicsWindow()
graphics_window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()