menator01
Gold Coder
Little project was playing around with.
You can download the image and sound files from github
requires pillow
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)