Wen*_*ang 3 python pygame button game-development
我想在我的游戏中创建一个可以控制背景音乐的按钮.第一次点击将停止背景音乐,第二次点击可以恢复音乐.现在我的按钮可以控制音乐的开启和关闭,但是我需要多次点击才能使它工作,似乎每次都没有捕获点击事件,这里是我的代码:
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if 20 + 50 > mouse_position[0] > 20 and 20 + 20 > mouse_position[1] > 20:
play_music = not play_music
if play_music:
pygame.mixer.music.unpause()
else:
pygame.mixer.music.pause()
pygame.display.flip()
clock = pygame.time.Clock()
clock.tick(15)
Run Code Online (Sandbox Code Playgroud)
看起来你有一个pygame.mixer.music.pause()但没有resume.我不确定pygame的音乐混音器是如何工作的,但我建议使用按钮点击更新的标志
music = 0默认情况下,如果单击,则设置music = 1然后检查if music == 1: pygame.mixer.music.pause()并执行if music == 0: pygame.mixer.music.unpause().每次单击按钮时进行检查并更改标记.
J0hn的回答是正确的.定义一个布尔变量(例如music_paused = False),当用户点击按钮并调用pygame.mixer.music.pause停止音乐并pygame.mixer.music.unpause恢复音乐流的播放时切换它.
我还建议在事件循环(for event in pygame.event.get():)中进行碰撞检查,因为每个pygame.MOUSEBUTTONDOWN事件只应单击一次按钮.pygame.mouse.get_pressed()只要鼠标按钮关闭,它就会一直点击音乐按钮.
import pygame as pg
pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
BLUE = pg.Color('dodgerblue1')
pg.mixer.music.load('your_music_file.ogg')
pg.mixer.music.play(-1)
button = pg.Rect(100, 150, 90, 30)
music_paused = False
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
elif event.type == pg.MOUSEBUTTONDOWN:
if button.collidepoint(event.pos):
# Toggle the boolean variable.
music_paused = not music_paused
if music_paused:
pg.mixer.music.pause()
else:
pg.mixer.music.unpause()
screen.fill(BG_COLOR)
pg.draw.rect(screen, BLUE, button)
pg.display.flip()
clock.tick(60)
pg.quit()
Run Code Online (Sandbox Code Playgroud)