当前位置:网站首页>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
边栏推荐
- Three deletion strategies and eviction algorithm of redis
- Voice controlled robot based on ROS (II): implementation of upper computer
- "When you are no longer a programmer, many things will get out of control" -- talk to SUSE CTO, the world's largest independent open source company
- 全链路灰度在数据库上我们是怎么做的?
- 瀚高数据库最佳实践配置工具HG_BP日志采集内容
- 融合数据库生态:利用 EventBridge 构建 CDC 应用
- Subcontracting loading of wechat applet
- Redis 3.0源码分析-数据结构与对象 SDS LIST DICT
- System. ArgumentException: Object of type ‘System. Int64‘ cannot be converted to type ‘System.Int32‘
- js飞入js特效弹窗登录框
猜你喜欢

如何平衡SQL中的安全与性能?

Unity package project to vs deploy hololens process summary

Why on earth is it not recommended to use select *?

Unity gadget displays the file size of the resource directory

Integrating database Ecology: using eventbridge to build CDC applications
![Leetcode:2141. The longest time to run n computers at the same time [the maximum value is two points]](/img/33/05620dfff2f6ac67691d20c5256c5b.png)
Leetcode:2141. The longest time to run n computers at the same time [the maximum value is two points]

Random talk on GIS data (VI) - projection coordinate system

漂亮的蓝色背景表单输入框样式

太空射击第11课: Sound and Music

不懂就问,快速成为容器服务进阶玩家!
随机推荐
太空射击第16课: 道具(Part 2)
Soft raid
研发效能的思考总结
Redis的三种删除策略以及逐出算法
Classes and objects (medium)
Why on earth is it not recommended to use select *?
UE4 3dui widget translucent rendering blur and ghosting problems
H5 wechat shooting game source code
“当你不再是程序员,很多事会脱离掌控”—— 对话全球最大独立开源公司SUSE CTO...
js图表散点图例子
Explain rigid body and collider components in unity
Unity object path query tool
JS picture hanging style photo wall JS special effect
"When you are no longer a programmer, many things will get out of control" -- talk to SUSE CTO, the world's largest independent open source company
Integrating database Ecology: using eventbridge to build CDC applications
Unity gadget displays the file size of the resource directory
如何平衡SQL中的安全与性能?
融合数据库生态:利用 EventBridge 构建 CDC 应用
[C语言刷题篇]链表运用讲解
平均海拔4000米!我们在世界屋脊建了一朵云