Insert score in a button game function

前端 未结 1 411
执念已碎
执念已碎 2021-01-24 09:48

I have this code for a button that is pressable:

def button(msg,xloc,yloc,xlong,ylong,b1,b2,action=None):

    hover = pygame.mouse.get_pos() 
    click = pygame         


        
1条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-24 10:42

    Here's the simplest way to implement a button that I know. Create a rect for the button and draw it with pygame.draw.rect (or blit an image). For the collision detection, check if the event.pos of a pygame.MOUSEBUTTONDOWN event collides with the rect and then just increment the score variable.

    import pygame as pg
    
    
    pg.init()
    screen = pg.display.set_mode((640, 480))
    
    GRAY = pg.Color('gray15')
    BLUE = pg.Color('dodgerblue1')
    
    
    def main():
        clock = pg.time.Clock()
        font = pg.font.Font(None, 30)
        button_rect = pg.Rect(200, 200, 50, 30)
    
        score = 0
        done = False
    
        while not done:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    done = True
                if event.type == pg.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        if button_rect.collidepoint(event.pos):
                            print('Button pressed.')
                            score += 1
    
            screen.fill(GRAY)
            pg.draw.rect(screen, BLUE, button_rect)
            txt = font.render(str(score), True, BLUE)
            screen.blit(txt, (260, 206))
    
            pg.display.flip()
            clock.tick(30)
    
    
    if __name__ == '__main__':
        main()
        pg.quit()
    

    Addendum: Actually, I would implement a button with the help of classes, sprites and sprite groups. If you don't know how classes and sprites work, I'd recommend to check out Program Arcade Games (chapter 12 and 13).

    import pygame as pg
    
    
    pg.init()
    GRAY= pg.Color('gray12')
    BLUE = pg.Color('dodgerblue1')
    FONT = pg.font.Font(None, 30)
    
    
    # The Button is a pygame sprite, that means we can add the
    # instances to a sprite group and then update and render them
    # by calling `sprite_group.update()` and `sprite_group.draw(screen)`.
    class Button(pg.sprite.Sprite):
    
        def __init__(self, pos, callback):
            pg.sprite.Sprite.__init__(self)
            self.image = pg.Surface((50, 30))
            self.image.fill(BLUE)
            self.rect = self.image.get_rect(topleft=pos)
            self.callback = callback
    
        def handle_event(self, event):
            """Handle events that get passed from the event loop."""
            if event.type == pg.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    print('Button pressed.')
                    # Call the function that we passed during the
                    # instantiation. (In this case just `increase_x`.)
                    self.callback()
    
    
    class Game:
    
        def __init__(self):
            self.screen = pg.display.set_mode((800, 600))
            self.clock = pg.time.Clock()
    
            self.x = 0
            self.button = Button((200, 200), callback=self.increase_x)
            self.buttons = pg.sprite.Group(self.button)
            self.done = False
    
        # A callback function that we pass to the button instance.
        # It gets called if a collision in the handle_event method
        # is detected.
        def increase_x(self):
            """Increase self.x if button is pressed."""
            self.x += 1
    
        def run(self):
            while not self.done:
                self.handle_events()
                self.run_logic()
                self.draw()
                self.clock.tick(30)
    
        def handle_events(self):
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    self.done = True
    
                for button in self.buttons:
                    button.handle_event(event)
    
        def run_logic(self):
            self.buttons.update()
    
        def draw(self):
            self.screen.fill(GRAY)
            self.buttons.draw(self.screen)
            txt = FONT.render(str(self.x), True, BLUE)
            self.screen.blit(txt, (260, 206))
    
            pg.display.flip()
    
    
    if __name__ == "__main__":
        Game().run()
        pg.quit()
    

    0 讨论(0)
提交回复
热议问题