Welcome to Code Forum!

Join a community that supports you and your coding journey from day one. We strive to be a friendly, supportive community that empowers everyone to be better developers. By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.

    GIF shows where to locate </> in the thread and or post editor toolbar.
    To learn more about how to use our BBCode feature, review our "How to post your code into threads" here.

    Thank you, Code Forum.

Simple pygame rain animation

menator01

Gold Coder
Little project was playing around with.
You can download the image and sound files from github

requires pillow

Python:
# Do the imports
import pygame
import os
from random import random, randint
from PIL import Image

# Initiate pygame
pygame.init()

# Path to executing script
path = os.path.realpath(os.path.dirname(__file__))

img = Image.open(f'{path}/rainbg.png')
size = img.width, img.height

# Setup the window
screen = pygame.display.set_mode((size))

# Itialize pygame mixer
pygame.mixer.init(frequency=44100, size=-16, channels=1)

# Sound files
thunder = pygame.mixer.Sound(f'{path}/thunder.mp3')
rain = pygame.mixer.Sound(f'{path}/rain.mp3')

# Create the channels
channel1 = pygame.mixer.Channel(0)
channel2 = pygame.mixer.Channel(1)

# pygame clock for frame rate
clock = pygame.time.Clock()

# Create the sprite group
raindrops = pygame.sprite.Group()

# Background for the window
bg = pygame.image.load(f'{path}/rainbg.png')

bg_rect = bg.get_rect()

# Text with shadow
font = pygame.font.SysFont(None, 60)

# Shadow
surf_shadow = font.render('Press r to start/stop rain', True, (30,30,30))

# Set regular text
surf = font.render('Press r to start/stop rain', True, (255,255,255))
surf_rect = surf.get_rect()

surf_rect.center = bg_rect.center


# Create the raindrop class
class Drop(pygame.sprite.Sprite):
    def __init__(self, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface([5, 10])
        self.image.fill((220,220,220))
    
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.speed = randint(10, 20)

    # Update raindrop fall
    def update(self):
        self.rect.y = self.rect.y + self.speed   


# Set some variables
start_rain = False
run = True
while run:
    # Blit the background image to the window
    screen.blit(bg, (0,0))
    screen.blit(surf_shadow, (surf_rect.left+2, 22))
    screen.blit(surf, (surf_rect.left, 20))

    # Get pygame events
    for event in pygame.event.get():

        # A way to exit
        if event.type == pygame.QUIT:
            run = False

        # Get key press
        if event.type == pygame.KEYDOWN and event.key == pygame.K_r:

            # If start rain is false set to true and start the rain animation and sound
            if  not start_rain:
                start_rain = True
                channel1.play(rain, loops=-1)

                # We need some raindrops in our group
                for i in range(150):
                    drop = Drop(randint(0, size[0]), randint(-10, size[1]))
                    raindrops.add(drop)

            # Else clear the group and stop the animation
            else:
                start_rain = False
                raindrops.empty()
                rain.stop()

    # If start_rain is true, start the thunder
    if start_rain:
        #if thunder is not playing already, start thunder
        if not channel2.get_busy():
            if start_rain:
                channel2.play(thunder)
    else:
        channel2.stop()
                
    # Kill the raindrop if it goes beyond screen height
    if start_rain:
        for drop in raindrops:
            if drop.rect.top > size[1]:
                drop.kill()
                raindrops.add(Drop(randint(0, size[0]), -10))

    # Update everything
    raindrops.update()
    raindrops.draw(screen)
    pygame.display.update()
    clock.tick(30)
 

Latest posts

Buy us a coffee!

Buy me a coffee.
Back
Top Bottom