How to make buttons in python/pygame?

前端 未结 5 1962
粉色の甜心
粉色の甜心 2020-12-16 22:35

I\'m making a game in pygame and on the first screen I want there to be buttons that you can press to (i) start the game, (ii) load a new screen with instructions, and (iii)

5条回答
  •  自闭症患者
    2020-12-16 23:15

    So you have to make a function named button which receives 8 parameters. 1)Message of button 2)X position of left top corner of the button 3)Y position of left top corner of the button 4)Width of the button 5)Height of button 6)Inactive color(background color) 7)Active color(color when you hover) 8)Name of the action you want to perfom

    def button (msg, x, y, w, h, ic, ac, action=None ):
        mouse = pygame.mouse.get_pos()
        click = pygame.mouse.get_pressed()
    
        if (x+w > mouse[0] > x) and (y+h > mouse[1] > y):
            pygame.draw.rect(watercycle, CYAN, (x, y, w, h))
            if (click[0] == 1 and action != None):
                if  (action == "Start"):
                    game_loop()
                elif  (action == "Load"):
                     ##Function that makes the loading of the saved file##
                elif  (action == "Exit"):
                    pygame.quit()
    
        else:
            pygame.draw.rect(watercycle, BLUE, (x, y, w, h))
            smallText = pygame.font.Font("freesansbold.ttf", 20)
            textSurf, textRect = text_objects(msg, smallText)
            textRect.center = ( (x+(w/2)), (y+(h/2)) )
            watercycle.blit(textSurf, textRect)
    

    So when you create your game loop and you call the button function:

    button ("Start", 600, 120, 120, 25, BLUE, CYAN, "Start" )

提交回复
热议问题