Bei pygame bietet sich für Ereignisse, die wiederholt nach einer bestimmten Zeit stattfinden sollen, ein Timer an:
https://www.pygame.org/docs/ref/time.ht ... .set_timer
Der Timer löst dann nach einem festgesetzten Intervall ein selbst definiertes Event aus, welches sich wie alle anderen in der Game-Loop abfragen läßt.
Code: Alles auswählen
from random import randint
import pygame as pg
SPAWN_PERIOD = 1000 # ms
class Ball:
def __init__(self, screen, color, radius, position, velocity, acceleration):
self.screen = screen
self.width = screen.get_width()
self.height = screen.get_height()
self.color = color
self.radius = radius
self.position = position
self.velocity = velocity
self.acceleration = acceleration
def update(self):
self.velocity += self.acceleration
self.position += self.velocity
if self.position.x < self.radius:
self.position.x = 2 * self.radius - self.position.x
self.velocity.x = -self.velocity.x
elif self.position.x > self.width - self.radius:
self.position.x = 2 * (self.width - self.radius) - self.position.x
self.velocity.x = -self.velocity.x
if self.position.y > self.height - self.radius:
self.position.y = 2 * (self.height - self.radius) - self.position.y
self.velocity.y = -self.velocity.y
def draw(self):
pg.draw.circle(self.screen, self.color, self.position, self.radius)
class Game:
def __init__(self, width, height):
self.running = False
# Ereignis registrieren
self.event = pg.event.Event(pg.event.custom_type())
self.width = width
self.height = height
self.screen = pg.display.set_mode((self.width, self.height))
self.balls = []
self.background = pg.Color(0, 0, 0)
def run(self):
clock = pg.time.Clock()
# Zeitintervall in Millisekunden zum Auslösen des Ereignisses festlegen
pg.time.set_timer(self.event, SPAWN_PERIOD)
self.running = True
self.spawn()
while self.running:
self.update()
self.draw()
self.process_events()
clock.tick(60)
pg.display.update()
def process_events(self):
for event in pg.event.get():
if event.type == pg.QUIT:
self.running = False
# Prüfen ob das Ereignis ausgelöst wurde
if event == self.event:
self.spawn()
def spawn(self):
radius = 10
x_position = randint(radius, self.width - radius)
x_velocity = randint(-2, 2)
self.balls.append(
Ball(
screen=self.screen,
color=pg.Color(255, 0, 0),
radius=radius,
position=pg.Vector2(x_position, 0),
velocity=pg.Vector2(x_velocity, 0),
acceleration=pg.Vector2(0, 0.1),
)
)
def update(self):
for ball in self.balls:
ball.update()
def draw(self):
self.screen.fill(self.background)
for ball in self.balls:
ball.draw()
if __name__ == "__main__":
pg.init()
Game(500, 500).run()