samedi 19 novembre 2022

Falling objects from random places in pygame

I want to make a program where objects fall from top of the screen and when reached bottom then turn left or right. Eventually then object in this case ball image is out of screen to the left or right. In other words to make objects fall like a rain drops and continue this until screen is closed. Here is my code so far:

import pygame
from random import randint

pygame.init()
width, height = 680, 480
display = pygame.display.set_mode((width, height))

clock = pygame.time.Clock()
ball = pygame.image.load("ball.png")
speed_y = 1

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
           exit()  

    list_of_balls = []
    for t in range(10):
        x = randint(0, width-ball.get_width())
        y = 0-ball.get_height()
        list_of_balls.append((x, y))

    display.fill((0, 0, 0))
    for b in list_of_balls:
        display.blit(ball, b)
    pygame.display.flip()

    if y < height-ball.get_height():
        y += speed_y
    else:
        direction = randint(0, 1)
        if direction == 0:
            x += 1
        if direction == 1:
            x -= 1

    clock.tick(60)

I've tried to make a list of balls and then randomly make them fall.




Aucun commentaire:

Enregistrer un commentaire