头图

Disclaimer: It is not easy to be original, and may not be reproduced without permission

xa

0. Preface

hello, friends! I'm still the cat lady who took you guys to write games.
Today is the 5th episode of this game! Did you all learn the first 4 episodes?
In the last episode, we changed the background picture of the game window, and the feeling will be different immediately. Today we add background music to the game, and then replace this little square with a little boy picking mushrooms. Alright, let's start the code.

1. Add background music to the game

Anyone who has played the game knows that background music is the soul of the game. In pygame , adding background music to the game is super simple, and you can do it with three lines of code !
The first line of code, use the pygame.mixer.init() function to complete the initialization.
The second line of code creates a sound object through the pygame.mixer.Sound() function. The mp3 audio file should be passed in the parentheses. We give the sound object a name, called bg_music .

 bg_music = pygame.mixer.Sound("./sound/mushroom.mp3")

The last line of code is to make the music play, we just need to call bg_music的play function.

 bg_music.play()

Ok, let's run the game to see the effect. The background music starts playing.

Did you notice it? There is also a problem here , the background music of the game is played in a loop, but here it is over once it is played. It is also very simple to make the music loop, we just need to pass -1 to the play() function, and that's it.

 bg_music.play(-1)

The effect of loop playback, I will not demonstrate it here.

2. Replace the small square with a picture of a little boy

Next, we replace the small square with a picture of a little boy.
In the image directory, I have prepared a picture of the little boy.
We need to modify the Player class, comment out the self.image and self.image.fill function two lines of code to load the picture of the little boy, so use
pygame.image.load() function to import the picture, the path of the little boy picture passed in the parentheses is assigned to self.image .

 class Player(pygame.sprite.Sprite):
    def __init__(self):
        super(Player, self).__init__()
        # self.image = pygame.Surface((60, 30))
        self.image = pygame.image.load("./image/player.png")
        # self.image.fill("white")
        self.rect = self.image.get_rect(left=WIDTH//2, top=HEIGHT//2)

We run the game to see the effect, we can see that the little boy has it, and the background music is also available. How is it, do you feel special?

Pay attention to Sister Cat, the next episode is coming soon.


猫姐_游戏编程
56 声望18 粉丝

😸猫姐,211硕士,定居成都的荆州人,5年IT生涯,教大家做益智小游戏,快乐学编程