Habib Ismail
Habib Ismail

Reputation: 47

How do I play MouseOver sound effect only once in pygame?

I am trying to play my sound only once when my mouse is over the the green button but it doesn't seem to work — plays repeatedly.

mouseisover = True
if greenbutton2.isOver(pos):
    window.blit(bls2,(0,0))
    if mouseisover:
        mouseover.play()
        mouseisover = False

my whole game _intro code at the main loop for my game intro first I set a mouseisover variable and made it True then after in my main loop I said if thats True then play the sound then under it I said mouseisover = False but still it plays my sound again and again none stop

# start screen
def game_intro():

    carsound = pygame.mixer.Sound("carsound1.wav") # 
    

    mouseisover = True
    mouseover = pygame.mixer.Sound("lols (2).wav") # MOUSEOVERSOUND


    class button():
        def __init__(self, color, x,y,width,height, text=''):
            self.color = color
            self.x = x
            self.y = y
            self.width = width
            self.height = height
            self.text = text

        def draw(self,window,outline=None):
            #Call this method to draw the button on the screen
            if outline:
                pygame.draw.rect(window, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0)
                
            pygame.draw.rect(window, self.color, (self.x,self.y,self.width,self.height),0)
            
            if self.text != '':
                font = pygame.font.SysFont('comicsans', 60)
                text = font.render(self.text, 1, (0,0,0))
                window.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))

        def isOver(self, pos):
            #Pos is the mouse position or a tuple of (x,y) coordinates
            if pos[0] > self.x and pos[0] < self.x + self.width:
                if pos[1] > self.y and pos[1] < self.y + self.height:
                    return True
                
            return False
        
    white = (250,250,250)
    greenbutton = button((0,255,0),60,449,200,80, 'Click Me )')
    greenbutton2 = button((0,255,0),50,518,200,80, 'Click Me )')
    greenbutton3 = button((0,255,0),50,600,200,70, 'Click Me )')

    bls2 = pygame.image.load("about2.png")
    bls3 = pygame.image.load("credits25.png")
    bls4 = pygame.image.load("playgame1.png")


    def fade(width, height): 
        fade = pygame.Surface((width, height))
        fade.fill((0,0,0))
        for alpha in range(0, 100):
            fade.set_alpha(alpha)
            window.blit(fade, (0,0))
            pygame.display.update()
            pygame.time.delay(15)

            
    def redraw():

        bls = pygame.image.load("bgs.png")
        window.blit(bls,(0,0))





    # this makes it             
    snow_list=[]
    no_of_circles=100;
    clock = pygame.time.Clock()
    FPS = 60
    clock.tick(FPS)
    for i in range(no_of_circles):
        x = random.randrange(0, 800)
        y = random.randrange(0, 700)
        snow_list.append([x,y])




            
    red = (200,0,0)
    green = (255,250,250)
    bright_red = (255,250,0)
    bright_green = (0,255,0)
    clock = pygame.time.Clock()
    intro = True
    while intro:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                intro = False
                pygame.quit()

       
        redraw()


        pos = pygame.mouse.get_pos()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if greenbutton.isOver(pos):
                fade(800,800)
                main_loop()


        pos = pygame.mouse.get_pos()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if greenbutton2.isOver(pos):
                window.blit(bls2,(0,0))
                fade(800,800)
                menu()

        if greenbutton2.isOver(pos):
            window.blit(bls2,(0,0))
            if mouseisover:
                mouseover.play()
                mouseisover = False


        if greenbutton3.isOver(pos):
            mouseover.play()
            window.blit(bls3,(0,0))

        if greenbutton.isOver(pos):
            mouseover.play()
            window.blit(bls4,(0,0))

            
        pos = pygame.mouse.get_pos()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if greenbutton3.isOver(pos):
                fade(800,800)
                creditss()





    # GAME INTRO IMAGE




        for point in snow_list:
            point[1]+=1
            pygame.draw.circle(window, (255,255,255), point, 2)

            if(point[1] >= 600):
                point[0] = random.randrange(0, 600)
                point[1] = random.randrange(-10, -5)

        clock.tick(FPS)


        partics()

      

        pygame.display.update()
 

Upvotes: 1

Views: 443

Answers (1)

OrioPrisco
OrioPrisco

Reputation: 48

It is difficult to answer without any more context, but my best guess is that this code is located in a loop.

This would mean that every time the loop runs, the variable mouseisover is assigned the value True, discarding the previous value.

Assuming this is your case you want to initialize your variable outside of the loop.

what your code looks like right now

    while (loop):
       mouseisover = True
       if greenbutton2.isOver(pos):
          window.blit(bls2,(0,0))
          if mouseisover:
             mouseover.play()
             mouseisover = False

what you should do

    mouseisover = True
    while (loop):
       if greenbutton2.isOver(pos):
          window.blit(bls2,(0,0))
          if mouseisover:
             mouseover.play()
             mouseisover = False

This, however, means that the sound will play only once and never again.

Update :
You can add a method like this to your button class :

    def playSoundIfMouseIsOver(self, pos, sound):
        if self.isOver(pos):
            if not self.over:
                sound.play()
                self.over = True
        else:
            self.over = False

and then to make them beep simply call playSoundIfMouseIsOver with the position of the mouse and the sound you want to play

        greenbutton2.playSoundIfMouseIsOver(pos, mouseover)
        greenbutton3.playSoundIfMouseIsOver(pos, mouseover)
        greenbutton.playSoundIfMouseIsOver(pos, mouseover)

This simply remembers the last value of isOver, and if it changes from False to True, it plays a sound.

These changes will require you to change every if that handled playing a sound with the new method

If you have more buttons you could place all your buttons inside a list and then iterate on the list to do the same action for every button

Creating the list (place this after creating the different buttons):

myButtonList = [greenbutton, greenbutton2, greenbutton3]

Iterating on that list (replaces the three similar lines) :

for myButton in myButtonList:
            myButton.playSoundIfMouseIsOver(pos, mouseover)

Also, I saw some weird stuff in your code, you have 4 button classes that are the exact same. You can define the button class a single time by simply placing it at the very beginning of the program, outside of any loop.

If you place your class definitions inside loops, they will only be accessible inside that loop!

Upvotes: 2

Related Questions