PyGame - How to get an image in the center of the screen

后端 未结 2 517
深忆病人
深忆病人 2021-01-29 00:25
# MENU
def gameMenu():
intro = True
while(intro == True):
    win.fill((0,0,0))
    iPATH = f\"{PATH}/assets/textures/titleScreen/buttons\"
    win.blit(pygame.image.loa         


        
2条回答
  •  执念已碎
    2021-01-29 01:18

    First of all, by convention, you should name your screen Surface simply screen.

    Then, you're loading the image files over and over again in the while loop. Just load it once.

    It's also good to (almost) always use convert after loading an image so the Surface will have the same pixel format as the screen.

    Finally, in pygame, you should use the Rect class for (almost) everything related to drawing/positioning.

    Here you can see how easy it is to center something using the Rect class. I also reordered your loop to follow the classic input/update/draw convention and removed the second image for brevity:

    def gameMenu():
    
        iPATH = f"{PATH}/assets/textures/titleScreen/buttons"
        logo = pygame.image.load(os.path.join(f"{iPATH}/Logo.png")).convert()
    
        logo_rect = logo.get_rect(center = screen.get_rect().center)
    
        while True:
    
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return
    
            keys = pygame.key.get_pressed()
            if keys[selectButton]:
                print("clicked z")
                break
            elif keys[backButton]:
                print("clicked x")
    
            screen.fill((0,0,0))
            screen.blit(logo, logo_rect)
            pygame.display.update()
    

提交回复
热议问题