当前位置:网站首页>Space shooting Lesson 11: sound and music
Space shooting Lesson 11: sound and music
2022-07-28 20:51:00 【acktomas】
Space shooting No 11 course : Sound and Music
This is us. “Shmup” Project No 8 part . If you haven't read through the previous section , Please from The first 1 part Start . In this lesson , We will add sound effects and music to the game .
video
You can watch the video of this course here :
The power of sound
Good audio is added to the game “ Fruit juice ” It's the most effective way to .Juice Is an informal game design word , Used to indicate something that makes the game interesting and fascinating . It is sometimes called “ The game feels ”.
Just like graphics , Finding the right sound for your game can be challenging .OpenGameArt It is a good place to find audio resources , It may be interesting to search for sound on the website , But we will study another way to create game sound effects .
Make a custom sound
We will use a name called Bfxr Great tool to generate Shmup The sound required for the game .Bfxr It looks like this :

Don't be intimidated by all these sliders and audio jargon names . The button on the left will randomly generate this type of sound . Try clicking “Shoot” Button several times . The generated sound will be saved in the list below the button .
about Shmup game , We need a “shoot” Sound and a “explosion” voice . Find the sound you need , single click “Export Wav” Button ( instead of “Save to Disk” Button ).
Next , We're going to create one “snd” Folder ( Just like what we do with images ), And will WAV Put the files there . The following is the voice I choose :
Please note that , There are two kinds of explosions . In this way , We can choose randomly among them , And there is a little change in the meteor explosion .
Last , We need some music . Browse at will OpenGameArt, Or you can use this :
Please note that , On the page above , The artist appointed “Attribution Instructions Contribution statement ”. These are the artists who will license your music . In short , This means that we must give respect to artists . We copy and paste this statement to the top of the program .
Add sound to the game
We are ready to add sound to the game . First , We need to specify the location of the sound folder :
# Frozen Jam by tgfcoder <https://twitter.com/tgfcoder> licensed under CC-BY-3
# Art from Kenney.nl
import pygame
import random
from os import path
img_dir = path.join(path.dirname(__file__), 'img')
snd_dir = path.join(path.dirname(__file__), 'snd')
Next , We need to load the sound file . We will do this at the same location where the graph is loaded . Let's do the shooting sound first :
# Load all game sounds
shoot_sound = pygame.mixer.Sound(path.join(snd_dir, 'pew.wav'))
Now? , We loaded the sound and assigned it to the variable shoot_sound, So that we can quote it . We hope that whenever players shoot, they can play sound , So let's add it to shoot() In the method :
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
shoot_sound.play()
That's all it's about . Now shooting feels much better !
Next , Let's add an explosion . We will load them and put them in a list :
# Load all game sounds
shoot_sound = pygame.mixer.Sound(path.join(snd_dir, 'pew.wav'))
expl_sounds = []
for snd in ['expl3.wav', 'expl6.wav']:
expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd)))
In order to make the explosion work , Whenever we destroy meteors , We all choose one of them at random :
# check to see if a bullet hit a mob
hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
for hit in hits:
score += 50 - hit.radius
random.choice(expl_sounds).play()
m = Mob()
all_sprites.add(m)
mobs.add(m)
music
The last thing to do is to add some background music , This will bring a lot of personality and emotion to the game . The way music works is slightly different from sound , Because you want it to stream continuously in the background .
First , Loading music :
expl_sounds = []
for snd in ['expl3.wav', 'expl6.wav']:
expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd)))
pygame.mixer.music.load(path.join(snd_dir, 'tgfcoder-FrozenJam-SeamlessLoop.ogg'))
pygame.mixer.music.set_volume(0.4)
This music file is quite loud , We don't want it to overwhelm other voices , So we also set the volume to the maximum 40%.
To play music , You just need to choose where the song should start in the code , In our case , This is before the game cycle starts :
score = 0
pygame.mixer.music.play(loops=-1)
# Game loop
running = True
loops Parameter is the way to specify the number of times you want the song to repeat . By setting loops by -1 Let it repeat indefinitely .
Try it - Isn't the game much better now ? We haven't changed any game playing , But music and sound effects bring a richer experience . Try different sounds , See how it affects the feel of the game .
In the next lesson , We will add some shields for players , So we won't die so easily .
The complete code of this part
# KidsCanCode - Game Development with Pygame video series
# Shmup game - part 8
# Video link: https://www.youtube.com/watch?v=abm1VwFxv9o
# Sound and Music
# Frozen Jam by tgfcoder <https://twitter.com/tgfcoder> licensed under CC-BY-3
# Art from Kenney.nl
import pygame
import random
from os import path
img_dir = path.join(path.dirname(__file__), 'img')
snd_dir = path.join(path.dirname(__file__), 'snd')
WIDTH = 480
HEIGHT = 600
FPS = 60
# define colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# initialize pygame and create window
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Shmup!")
clock = pygame.time.Clock()
font_name = pygame.font.match_font('arial')
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.transform.scale(player_img, (50, 38))
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.radius = 20
# pygame.draw.circle(self.image, RED, self.rect.center, self.radius)
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
self.speedx = 0
def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -8
if keystate[pygame.K_RIGHT]:
self.speedx = 8
self.rect.x += self.speedx
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
def shoot(self):
bullet = Bullet(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
shoot_sound.play()
class Mob(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image_orig = random.choice(meteor_images)
self.image_orig.set_colorkey(BLACK)
self.image = self.image_orig.copy()
self.rect = self.image.get_rect()
self.radius = int(self.rect.width * .85 / 2)
# pygame.draw.circle(self.image, RED, self.rect.center, self.radius)
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-150, -100)
self.speedy = random.randrange(1, 8)
self.speedx = random.randrange(-3, 3)
self.rot = 0
self.rot_speed = random.randrange(-8, 8)
self.last_update = pygame.time.get_ticks()
def rotate(self):
now = pygame.time.get_ticks()
if now - self.last_update > 50:
self.last_update = now
self.rot = (self.rot + self.rot_speed) % 360
new_image = pygame.transform.rotate(self.image_orig, self.rot)
old_center = self.rect.center
self.image = new_image
self.rect = self.image.get_rect()
self.rect.center = old_center
def update(self):
self.rotate()
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
class Bullet(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = bullet_img
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10
def update(self):
self.rect.y += self.speedy
# kill if it moves off the top of the screen
if self.rect.bottom < 0:
self.kill()
# Load all game graphics
background = pygame.image.load(path.join(img_dir, "starfield.png")).convert()
background_rect = background.get_rect()
player_img = pygame.image.load(path.join(img_dir, "playerShip1_orange.png")).convert()
bullet_img = pygame.image.load(path.join(img_dir, "laserRed16.png")).convert()
meteor_images = []
meteor_list = ['meteorBrown_big1.png', 'meteorBrown_med1.png', 'meteorBrown_med1.png',
'meteorBrown_med3.png', 'meteorBrown_small1.png', 'meteorBrown_small2.png',
'meteorBrown_tiny1.png']
for img in meteor_list:
meteor_images.append(pygame.image.load(path.join(img_dir, img)).convert())
# Load all game sounds
shoot_sound = pygame.mixer.Sound(path.join(snd_dir, 'pew.wav'))
expl_sounds = []
for snd in ['expl3.wav', 'expl6.wav']:
expl_sounds.append(pygame.mixer.Sound(path.join(snd_dir, snd)))
pygame.mixer.music.load(path.join(snd_dir, 'tgfcoder-FrozenJam-SeamlessLoop.ogg'))
pygame.mixer.music.set_volume(0.4)
all_sprites = pygame.sprite.Group()
mobs = pygame.sprite.Group()
bullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(8):
m = Mob()
all_sprites.add(m)
mobs.add(m)
score = 0
pygame.mixer.music.play(loops=-1)
# Game loop
running = True
while running:
# keep loop running at the right speed
clock.tick(FPS)
# Process input (events)
for event in pygame.event.get():
# check for closing window
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shoot()
# Update
all_sprites.update()
# check to see if a bullet hit a mob
hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
for hit in hits:
score += 50 - hit.radius
random.choice(expl_sounds).play()
m = Mob()
all_sprites.add(m)
mobs.add(m)
# check to see if a mob hit the player
hits = pygame.sprite.spritecollide(player, mobs, False, pygame.sprite.collide_circle)
if hits:
running = False
# Draw / render
screen.fill(BLACK)
screen.blit(background, background_rect)
all_sprites.draw(screen)
draw_text(screen, str(score), 18, WIDTH / 2, 10)
# *after* drawing everything, flip the display
pygame.display.flip()
pygame.quit()
The first 9 part : shield
边栏推荐
- [C language brush questions] explanation of linked list application
- 太空射击第15课: 道具
- js可拖拽alert弹窗插件
- 阿里云 MSE 支持 Go 语言流量防护
- Yyds dry inventory interview must brush top101: every k nodes in the linked list are turned over
- Lvs+keepalived high availability deployment practical application
- 不懂就问,快速成为容器服务进阶玩家!
- 太空射击第11课: Sound and Music
- JS picture hanging style photo wall JS special effect
- Leetcode:2141. The longest time to run n computers at the same time [the maximum value is two points]
猜你喜欢

EasyNLP中文文图生成模型带你秒变艺术家

js可拖拽alert弹窗插件

Ask if you don't understand, and quickly become an advanced player of container service!

Unity gadget displays the file size of the resource directory

《软件设计师考试》易混淆知识点

阿里云 MSE 支持 Go 语言流量防护

JS win7 transparent desktop switching background start menu JS special effect
![[server data recovery] HP StorageWorks series storage RAID5 two disk failure offline data recovery case](/img/7c/d5643d27c2ca7a7aed4eb02fd81042.jpg)
[server data recovery] HP StorageWorks series storage RAID5 two disk failure offline data recovery case

js图表散点图例子

什么是数据中台?数据中台带来了哪些价值?_光点科技
随机推荐
Explain several mobile ways of unity in detail
Oracle library access is slow. Why?
Cartoon JS shooting game source code
Unity package exe to read and write excel table files
作业 ce
How bad can a programmer be? Nima, they are all talents
Redis review summary
阿里云 MSE 支持 Go 语言流量防护
Establishment of flask static file service
[C语言刷题篇]链表运用讲解
Introduction to redis I: redis practical reading notes
leetcode:2141. 同时运行 N 台电脑的最长时间【最值考虑二分】
卡通js射击小游戏源码
Raspberry pie 4B uses MNN to deploy yolov5 Lite
Unity gadget displays the file size of the resource directory
Use of DDR3 (axi4) in Xilinx vivado (4) incentive design
Lvs+keepalived high availability deployment practical application
Use order by to sort
Integrating database Ecology: using eventbridge to build CDC applications
Three deletion strategies and eviction algorithm of redis