Reputation: 127
I made a background music ingame, i put a volume muted & unmuted sprite and made it clickable, When you mute the music, i want screen.blit(unmute) to disappear.
Source Code:
...
x = 0
pygame.mixer.music.load("soundtrack.wav")
volume = pygame.image.load("volume.png")
mute = pygame.image.load("mute.png")
resized_volume = pygame.transform.scale(volume, (100, 100))
resized_mute = pygame.transform.scale(mute, (100,100))
pygame.mixer.music.play(-1,0.0)
while Loop: # main game loop
...
if event.type == MOUSEBUTTONDOWN:
if event.button == 1: # 1 == left
vol_rect = volume.get_rect(topleft = (700,500))
if vol_rect.collidepoint(event.pos):
x += 1
if x > 2:
x = 1
if x == 1:
screen.blit(mute,(700,500))
pygame.mixer.music.pause()
else:
if x == 2:
screen.blit(volume, (700,500))
pygame.mixer.music.unpause()
...
pygame.quit()
sys.exit()
Upvotes: 0
Views: 312
Reputation: 159
I didn't try but I hope it works:
class MuteUnmute_Button:
def __init__(self):
self.x = 500
self.y = 400
self.state = True
self.mute_image = pygame.image.load("mute_image.png")
self.unmute_image = pygame.image.load("unmute_image.png")
self.image = mute_image
self.screen = screen
def redraw(self):
self.screen.blit(self.image,(self.x,self.y))
def checkCollision(self):
rect = self.image.get_rect()
return rect.collidepoint(pygame.mouse.pos)
def changeImage(self):
if self.state:
self.image = self.mute_image
else:
self.image = self.unmute_image
mute_unmute_button = MuteUnmuteButton()
while Loop:
for event in pygame.event.get():
if event.type == MOUSEBUTTONDOWN:
if event.button == 1:
if mute_unmute_button.checkCollision():
if mute_unmute_button.state:
mute_unmute_button.state = False
mute_unmute_button.changeImage()
pygame.mixer.music.pause()
else:
mute_unmute_button.state = True
mute_unmute_button.changeImage()
pygame.mixer.music.unpause()
screen.fill((255,255,255)) #Fills background
mute_unmute_button.redraw()
pygame.display.flip()
I gave a example, you can change code for your program.
Upvotes: 1
Reputation: 210909
You have to redraw the scene in every frame. Draw the sprites depending on the value of the variable x
. e.g.:
while Loop: # main game loop
# [...]
if event.type == MOUSEBUTTONDOWN:
if event.button == 1: # 1 == left
# [...]
# [...]
if x == 0:
# [...] draw something different
elif x == 1:
screen.blit(mute,(700,500))
elif x == 2:
screen.blit(volume, (700,500))
# [...]
Upvotes: 1