一、引言
前面的游戏玩法写得差不多,但游戏没有音效,趣味性不够。本节中我们将在游戏中增加音效。
二、实现思路
作为普通码农,我们很多时候工作就是搬运工。pygame是成熟的库,像音效这种简单功能,pygame一定帮我们实现好了,我们要做就是通过搜索引擎或者文档找到相应的api。对api的使用,不建议去死记硬背,而应该重在理解,多问问自己,如果自己来设计这个api,需要携带哪几个参数,然后对比库函数给的参数,这也是个学习的过程。
crash_sound = pygame.mixer.Sound("crashed.wav") # 加载声音
crash_sound.play() # 调用play()函数播放
可以看到,pygame的音效处理函数与字体api其实差不多,都是先load相应的音频文件,在需要播放的地方调用play函数即可。
实现代码为:
import pygame, sys
import random
# 初始化
pygame.init()
SCREEN = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
# 绿色方块固定在最下方,左右移动,y值不变
green_x = 110
# 红色方块从上往下移动,x值不变
red_y = 0
# 游戏主循环
score = 0
pygame.font.init()
myfont = pygame.font.Font(None,60)
red_x = 35
life_times, is_over = 3, False
while True:
for event in pygame.event.get():
# 处理退出事件
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 键盘按下事件
elif event.type == pygame.KEYDOWN:
# 'a'键被按下
if event.key == pygame.K_a:
green_x -= 5
elif event.key == pygame.K_d:
green_x += 5
red_y += 5
green_rect = pygame.Rect(green_x, 250, 100, 50)
if green_rect.colliderect(red_x, red_y, 20, 50):
print('红色方块与绿色方块碰撞到了')
# 为了方便看到碰撞结果,直接break返回
score += 1
red_y = 0
red_x = random.randint(50, 350)
if red_y >= 300:
life_times -= 1
if life_times <= 0:
is_over = True
red_y = 0
red_x = random.randint(50, 350)
SCREEN.fill((255, 255, 255))
# 调用 pygame.display.update() 方法更新整个屏幕的显示
pygame.draw.rect(SCREEN, (255, 0, 0), (red_x, red_y, 20, 50))
pygame.draw.rect(SCREEN, (0, 255, 0), (green_x, 250, 100, 50))
textImage = myfont.render("score: " + str(score), True, (0, 0, 255))
SCREEN.blit(textImage, (10,10))
if is_over:
gameOverTextImage = myfont.render('GAME OVER!', True, (255, 0, 0))
SCREEN.blit(gameOverTextImage, (80,150))
pygame.display.update()
pygame.time.delay(50)
三、思考题
- 目前只有成功的时候有音乐,增加在失败条件播放失败的音效。