Simple Sprites, Music, Sound Example in Pygame

I recommend you guys check out this post first, since this post reuse most of the code from that post.

Let’s get started.

Sprite is just an image that is drawn over and over again in a game. With Pygame, you can easily load and draw an image onto the screen. First you need to have a frame first, it’s usually  a Rect, then you load the image into the game by using pygame.image.load(path) method, next use the Surface’s method blit() to get the image cover the Rect.

player = pygame.Rect(300,80,40,40)
player_image = pygame.image.load(path)
# draw the image over the Rect
window_interface.blit(player_image, player)

Music is loaded and play over and over again in a game. There’s always a music file in a game, because it’s consume lot of memory, if you have more than one music file in a game, your game probably surfer lagging.
Here’s how you load music and play it in Pygame
-1 means music loops forever

pygame.mixer.music.load('path') # load music
pygame.mixer.music.play(loops=-1, start=0.0) # play music with loops turned on and start at 0.0
# if you can stop music while it playing
pygame.mixer.music.stop()
# ... and replay it again
pygame.mixer.music.play(-1, 0.0)

Sound is a short music file, literally. It’s played when an even occurs, like a button clicked, player collect new item, etc. You load sound and store its reference in a variable, then you can play it what ever you want.
Example:

# load sound and store reference in a variable
sound = pygame.mixer.Sound(path)
# game loop
while True:
    for event in pygame.event.get():
        if event.type == KEYUP:
            if event.key == ord('m'):
                sound.play()

Apply those code into our previous example:

import pygame, sys
import random as rd
from pygame.locals import *

# set up pygame
pygame.init()

# set up window
WINDOW_WIDTH = 400
WINDOW_HEIGHT = 400
window_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), 0, 32)
pygame.display.set_caption('Sprites and Sound')
game_clock = pygame.time.Clock()

# set up direction
move_left = False
move_up = False
move_right = False
move_down = False
MOVEMENT_SPEED = 4

# set up colors
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
SIZE = 20
counter = 0

bouncer = pygame.Rect(300, 80, 40, 40)
# load and resize the image to fit the size of bouncer
bouncer_image = pygame.transform.scale(pygame.image.load('player.png'), (40, 40))
food_image = pygame.image.load('cherry.png')

foods = []
for i in xrange(20):
    foods.append(pygame.Rect(rd.randint(0, WINDOW_WIDTH), rd.randint(0, WINDOW_HEIGHT), SIZE, SIZE))

# set up music
pickup_sound = pygame.mixer.Sound('pickup.wav')
pygame.mixer.music.load('background.mid')
pygame.mixer.music.play()
music_playing = True

def check_overlap(rect1, rect2):
    """
    :param rect1: pygame rectangle
    :param rect2: pygame rectangle
    :return: True if rect1 overlap rect2
    """
    # check if one of four corners of rect1 is inside rect2
    for a, b in ([rect1, rect2], [rect2, rect1]):
        if is_point_inside_rect(a.left, a.top, b) \
        or is_point_inside_rect(a.left, a.bottom, b) \
        or is_point_inside_rect(a.right, a.top, b) \
        or is_point_inside_rect(a.right, a.bottom, b):
            return True
    else:
        return False

def is_point_inside_rect(x, y, rect):
    return (x > rect.left and x < rect.right and y > rect.top and y < rect.bottom)

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

        if event.type == KEYDOWN:
            if event.key == K_LEFT or event.key == ord('a'):
                move_left = True
                move_right = False
            if event.key == K_RIGHT or event.key == ord('d'):
                move_right = True
                move_left = False
            if event.key == K_UP or event.key == ord('w'):
                move_up = True
                move_down = False
            if event.key == K_DOWN or event.key == ord('s'):
                move_down = True
                move_up = False
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()
            if event.key == K_LEFT or event.key == ord('a'):
                move_left = False
            if event.key == K_RIGHT or event.key == ord('d'):
                move_right = False
            if event.key == K_UP or event.key == ord('w'):
                move_up = False
            if event.key == K_DOWN or event.key == ord('s'):
                move_down = False
            # check if player want to mute music
            if event.key == ord('m'):
                if music_playing:
                    pygame.mixer.music.stop()
                else:
                    pygame.mixer.music.play(-1, 0.0)
                music_playing = not music_playing

        if event.type == MOUSEBUTTONUP:
            foods.append(pygame.Rect(event.pos[0], event.pos[1], SIZE, SIZE))


    window_surface.fill(BLACK) # set background color of window to black

    # move the bouncer
    if move_down and bouncer.bottom < WINDOW_HEIGHT:
        bouncer.top += MOVEMENT_SPEED
    if move_up and bouncer.top > 0:
        bouncer.top -= MOVEMENT_SPEED
    if move_left and bouncer.left > 0:
        bouncer.left -= MOVEMENT_SPEED
    if move_right and bouncer.right < WINDOW_WIDTH:
        bouncer.right += MOVEMENT_SPEED

    # draw the bouncer
    #pygame.draw.rect(window_surface, GREEN, bouncer)
    window_surface.blit(bouncer_image, bouncer)

    # check collisions between foods and bouncer
    for food in foods[:]:
        if bouncer.colliderect(food):
            foods.remove(food)
            pickup_sound.play()

    # draw 'foods'
    for food in foods:
        #pygame.draw.rect(window_surface, BLUE, food)
        window_surface.blit(food_image, food)
    # after each 40 loops, we add new food
    counter += 1
    if counter > 20:
        counter = 0
        foods.append(pygame.Rect(rd.randint(0, WINDOW_WIDTH), rd.randint(0, WINDOW_HEIGHT), SIZE, SIZE))

    # draw the window onto the screen
    pygame.display.update()
    # sleep 0.02 second (around 50 frame per seconds)
    game_clock.tick(40) # 40 frame per second


Files: Download
Run to see how fun it is.
Feel free to donate me, since I’m a poor coder (that’s why I’m still using free wordpress domain) 😦

Advertisements