Add Background Music and text to PyGame

Add Background Music-and text to PyGame

So, far we have learned how to add images and mechanics to our game. In this article, we will be learning to add Background Music and text to PyGame. So, do the following changes in the final code that we got in our previous article after adding movement.

Adding text to PyGame window:

Now, adding text inside our game window is pretty much different than we did to add images.

To add texts, we need to specify the font that we want to use, the position where we want to put our image, then we need to render it to create an image and then we can blit it on our screen/window.

First, let’s create the variables that contain the text and X and Y coordinate of the text. It should be declared before the game loop:

text = "copyassignment"
textX = 10
textY = 10

Now we need to specify a font.

To do that, we need to use the font module that is provided to us by pygame. It is used to load and render the fonts. And the method that we will be using is Font().

Font() method is used to load a new font from a given filename or a Python file object. The size is the height of the font in pixels. If the filename is None the pygame default font will be loaded. If a font cannot be loaded from the arguments given an exception will be raised. Once the font is created the size cannot be changed.

Font objects are mainly used to render the text into new Surface objects. The render can emulate bold or italic features, but it is better to load from a font with actual italic or bold glyphs. The rendered text can be regular strings or Unicode.

It’s syntax is:

Font(filename, size) -> Font
Font(object, size) -> Font

Some different functions of Font() method are given below:

pygame.font.Font.boldGets or sets whether the font should be rendered in (faked) bold.
bold -> bool
pygame.font.Font.italicGets or sets whether the font should be rendered in (faked) italics.
italic -> bool
pygame.font.Font.underlineGets or sets whether the font should be rendered with an underline.
underline -> bool
pygame.font.Font.renderdraw text on a new Surface
render(text, antialias, color, background=None) -> Surface
pygame.font.Font.sizedetermine the amount of space needed to render text
size(text) -> (width, height)
pygame.font.Font.set_underlinecontrol if text is rendered with an underline
set_underline(bool) -> None
pygame.font.Font.get_underlinecheck if text will be rendered with an underline
get_underline() -> bool
pygame.font.Font.set_boldenable fake rendering of bold text
set_bold(bool) -> None
pygame.font.Font.get_boldcheck if text will be rendered bold
get_bold() -> bool
pygame.font.Font.set_italicenable fake rendering of italic text
set_italic(bool) -> None
pygame.font.Font.metricsgets the metrics for each character in the passed string
metrics(text) -> list
pygame.font.Font.get_italiccheck if the text will be rendered italic
get_italic() -> bool
pygame.font.Font.get_linesizeget the line space of the font text
get_linesize() -> int
pygame.font.Font.get_heightget the height of the font
get_height() -> int
pygame.font.Font.get_ascentget the ascent of the font
get_ascent() -> int
pygame.font.Font.get_descentget the descent of the font
get_descent() -> int
Information gathered from Pygame Docs.

So, now let’s load our font using the following command:

# We are using an inbuilt font (freesansbold.ttf) provided to us by Pygame
font = pygame.font.Font('freesansbold.ttf',24)

Now we need to render our font with our text. We can do it easily by using render() from the Font() method. The render() method is used to draw the text on a surface, which is the screen/window in our case.

render() takes 4 arguments:

render(text, antialias, color, background=None) -> Surface

This creates a new surface with the specified text rendered on it. pygame provides no way to directly draw text on an existing Surface: instead, you must use Font.render() to create an image (Surface) of the text, then blit this image onto another surface.

The Surface returned will be of the dimensions required to hold the text. (the same as those returned by Font.size()). If an empty string is passed for the text, a blank surface will be returned that is zero pixels wide and the height of the font.

Depending on the type of background and antialiasing used, this returns different types of Surfaces. For performance reasons, it is good to know what type of image will be used. If antialiasing is not used, the return image will always be an 8-bit image with a two-color palette. If the background is transparent a color key will be set. Antialiased images are rendered to 24-bit RGB images. If the background is transparent a pixel alpha will be included.

Optimization: if you know that the final destination for the text (on the screen) will always have a solid background, and the text is antialiased, you can improve performance by specifying the background color. This will cause the resulting image to maintain transparency information by color key rather than (much less efficient) alpha values.

If you render ‘\n‘ an unknown char will be rendered. Usually a rectangle. Instead, you need to handle newlines yourself.

Font rendering is not thread-safe: only a single thread can render text at any time.

So, now let’s render our font and text using the following code:

textImage = font.render(text, True, (255,255,255))

Now let’s blit it onto our display window/screen using the following command:

screen.blit(textImage, (textX, textY))

You final code should look like this:

import pygame

pygame.init()

screen = pygame.display.set_mode((800,600))
# Title
pygame.display.set_caption("copyassignment")
isRunning = True

#Loading image
player = pygame.image.load('athlete.png')


# Creating Text
# We are using an inbuilt font (freesansbold.ttf) provided to us by Pygame
text = "copyassignment"
font = pygame.font.Font('freesansbold.ttf',24)
textX = 10
textY = 10
textImage = font.render(text, True, (255,255,255))

#Specifying the X and Y Coordinate

playerX = 375
playerY = 500
Xchange = 0
Ychange = 0
while(isRunning ==True):
    screen.fill((167,145,55))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            isRunning = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                Ychange-=0.5
            if(event.key == pygame.K_DOWN):
                Ychange+=0.5
            if event.key == pygame.K_LEFT:
                Xchange-=0.5
            if event.key == pygame.K_RIGHT:
                Xchange+=0.5
        if event.type == pygame.KEYUP:
            Ychange=0
            Xchange=0
    if playerX+Xchange>775 or playerY+Ychange>565 or playerX+Xchange<0 or playerY+Ychange<0:
        playerY+=0
        playerX+=0
    else:
        playerY+=Ychange
        playerX+=Xchange
    screen.blit(textImage,(textX, textY))
    screen.blit(player,(playerX, playerY))
    pygame.display.update()

Adding Sound to our game:

Before adding sound to your game make sure that you have a sound file in .wav format in your working directory.

Now there are many options that how you want to play your sound. You can either play it in a loop like background music or once when a certain event occurs.

Adding sound in background:

To add sound in the background we need to use the mixer.music module from the pygame library.

The first this we need to do is to load the sound to our python file. And the method that we are going to use load(). This will load your file and prepare it for playback. If a music stream is already playing it will be stopped. This does not start the music playing.

load() takes one argument that is the file name. We can simply load the sound by using the following code:

# Loading the audio file
mixer.music.load('sound.wav')

Now, I want it to play in the background, so I will use the play() function. It starts the playback of the music stream. This will play the loaded music stream. If the music is already playing it will be restarted.

play() takes 3 arguments that are the following:

play(loops=0, start=0.0, fade_ms = 0) -> None

This will play the loaded music stream. If the music is already playing it will be restarted.

loops is an optional integer argument, which is 0 by default, it tells how many times to repeat the music. The music repeats indefinately if this argument is set to -1.

start is an optional float argument, which is 0.0 by default, which denotes the position in time, the music starts playing from. The starting position depends on the format of the music played. MP3 and OGG use the position as time in seconds. For mp3s the start time position selected may not be accurate as things like variable bit rate encoding and ID3 tags can throw off the timing calculations. For MOD music, it is the pattern order number. Passing a start position will raise a NotImplementedError if the start position cannot be set.

fade_ms is an optional integer argument, which is 0 by default, makes the music started playing at 0 volume and fade up to full volume over the given time. The sample may end before the fade-in is complete.

Now to play the music, we will write the following code:

# Playing the Audio file
mixer.music.play(-1)
# We have written -1 because it is the code to play the music in loop.

Your final code should be looking like this:

import pygame
from pygame import mixer
pygame.init()

screen = pygame.display.set_mode((800,600))
# Title
pygame.display.set_caption("copyassignment")
isRunning = True

#Loading image
player = pygame.image.load('athlete.png')
# Loading the audio file
mixer.music.load('sound.wav')
# Playing the Audio file
mixer.music.play(-1)
# We have written -1 because it is the code to play the music in loop.
# Creating Text
# We are using an inbuilt font (freesansbold.ttf) provided to us by Pygame
text = "copyassignment"
font = pygame.font.Font('freesansbold.ttf',24)
textX = 10
textY = 10
textImage = font.render(text, True, (255,255,255))

#Specifying the X and Y Coordinate

playerX = 375
playerY = 500
Xchange = 0
Ychange = 0
while(isRunning ==True):
    screen.fill((167,145,55))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            isRunning = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                Ychange-=0.5
            if(event.key == pygame.K_DOWN):
                Ychange+=0.5
            if event.key == pygame.K_LEFT:
                Xchange-=0.5
            if event.key == pygame.K_RIGHT:
                Xchange+=0.5
        if event.type == pygame.KEYUP:
            Ychange=0
            Xchange=0
    if playerX+Xchange>775 or playerY+Ychange>565 or playerX+Xchange<0 or playerY+Ychange<0:
        playerY+=0
        playerX+=0
    else:
        playerY+=Ychange
        playerX+=Xchange
    screen.blit(textImage,(textX, textY))
    screen.blit(player,(playerX, playerY))
    pygame.display.update()

Now, compile it and run it.

Adding sound effect:

To add sound effect we, use mixer.Sound to load the file and then we use .play() to play the sound.

Now we can simply load our music inside a variable using the following code:

# Loading our sound
hitSound = mixer.Sound('sound.wav')

Now we can simply play it once by writing the following code:

# Playing our sound
hitSound.play()
# Notice that we have not written -1 inside the parenthesis

As we want this sound to play when we touch any boundary, so what we will do is that we will put this code snippet inside the if statement inside our loop where we checked if the player has reached the boundary or not.

So our final code must be looking like this:

import pygame
from pygame import mixer
pygame.init()

screen = pygame.display.set_mode((800,600))
# Title
pygame.display.set_caption("copyassignment")
isRunning = True

#Loading image
player = pygame.image.load('athlete.png')

# Creating Text
# We are using an inbuilt font (freesansbold.ttf) provided to us by Pygame
text = "copyassignment"
font = pygame.font.Font('freesansbold.ttf',24)
textX = 10
textY = 10
textImage = font.render(text, True, (255,255,255))

#Specifying the X and Y Coordinate

playerX = 375
playerY = 500
Xchange = 0
Ychange = 0
while(isRunning ==True):
    screen.fill((167,145,55))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            isRunning = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                Ychange-=0.5
            if(event.key == pygame.K_DOWN):
                Ychange+=0.5
            if event.key == pygame.K_LEFT:
                Xchange-=0.5
            if event.key == pygame.K_RIGHT:
                Xchange+=0.5
        if event.type == pygame.KEYUP:
            Ychange=0
            Xchange=0
    if playerX+Xchange>775 or playerY+Ychange>565 or playerX+Xchange<0 or playerY+Ychange<0:
        playerY+=0
        playerX+=0
        hitSound = mixer.Sound('sound.wav')
        hitSound.play()
    else:
        playerY+=Ychange
        playerX+=Xchange
    screen.blit(textImage,(textX, textY))
    screen.blit(player,(playerX, playerY))
    pygame.display.update()

Now run it and test it. It will definitely work.

So that was all for this article, we hope to see you in our next articles. Until then, enjoy learning.

Check this video for more:

Credits to buildwithpython


Also read:

  • Games in Python | Assignment Expert
  • Creating a Pong Game using Python Turtle
    Introduction Today, we are going to create a Pong Game using Python Turtle. Pong is a well-known computer game that is similar to table tennis. The two players in this game control the two paddles on either side of the game window. To hit the moving ball, they move the paddles up and down. A…
  • Balloon Shooter Game using Python PyGame
    We all know the importance of the pygame library in terms of game development. We know that Pygame is a collection of Python modules for making video games. It is a collection of computer graphics and sound libraries for the Python programming language. Pygame is well suited to the development of client-side applications that may…
  • Complete PyGame Tutorial and Projects
    Without a doubt, we can say that Python is a multi-purpose language. Ranging from basic programming to its application in Data Science, from Machine Learning to Artificial Intelligence, and also in Developing Games. In simple words, it’s the language that is incomparable.With knowing the advantages of Python, today, in this article of Complete PyGame Tutorial…
  • Flappy Bird In Python Pygame with source code
    OVERVIEW OF THE PROJECT Hi there, welcome to the copyassignment hope you all are doing wonderful. Today, we are here to make a very interesting game Flappy Bird In Python Pygame. Hope you are familiar with this entertaining and very fascinating game. We would see how we can code the game Flappy bird from Scratch….
  • Complete Racing Game In Python Using PyGame
    So far we have learned a lot but there is not anything to end our game and now we are now going to see part 2 of our project. So, in this section, we will Create a Complete Racing Game In Python Using PyGame. So that we can use it to quit our game. Detecting…
  • Complete Game In PyGame and Python
    Now, it’s time to create our fully featured Complete Game In PyGame and Python with all the knowledge that we have gained from this series of articles. If you have seen the overview of our game, then maybe you have already made it. If yes then congrats, or you can follow along. To create this…
  • Python Complete Setup for Pygame
    Now, it’s time to install the tools that we will use to write programs. So, we will be learning Python Complete Setup for Pygame in this article. Let’s start. 1. Installing Python first. First, we need to go to the official site of python: https://www.python.org/ Now we need to go to the downloads page of…
  • Overview of our First Game Project
    So, congratulations, after learning all the basic and essential concepts of our pygame series, you are finally here to get the Overview of our First Game Project In this article, we will get to know about what game we are gonna make in the next article. But before that, in this article, we will try…
  • Car Race Game in PyGame Python: From Scratch
    Check the video below to know about our Car Race Game in PyGame and Python we are going to make. If you don’t know Pygame, then you should not worry, we will guide you from scratch. You just need some basic Python skills, other than Python, we will guide you with everything. Introduction to Car…
Share:

Author: Ayush Purawr