how to use pygame set_alpha() on a picture

前端 未结 3 547
暖寄归人
暖寄归人 2020-12-06 13:38

I am using pygame and python for a project I am building, and I am building a splashscreen for when the game first opens. I have a .png that I want to show for the splashscr

3条回答
  •  盖世英雄少女心
    2020-12-06 14:01

    [1] You don't want to load the image every iteration. Because creating a new surface is a slow operation. [2] Your loop draws 225 times, then afterward the final iteration, waits 2000ms.

    You want:

    image = pygame.image.load("logo.png")
    
    for i in range (225):
        background.fill((0,0,0))    
        image.set_alpha(i)
        screen.blit(image,(0,0))
        pygame.display.flip()
        pygame.time.delay(20)
    

    To fade in and out, you need to keep looping until the player clicks/hits a button. Like this:

    import pygame
    from pygame.locals import *
    
    # ...
    
    def title_loop():
        # title screen main loop    
        image = pygame.image.load("logo.png")
        done = False
        alpha = 0
        alpha_vel = 1
    
        # fade alpha in-out while waiting    
        while not done:        
            # get key input
            for event in pygame.event.get():
                if event.type == QUIT:
                    done = true
                if event.type == KEYDOWN:
                    if event.key = K_ESCAPE:
                        done = true
    
            # draw
            if alpha >= 255 or alpha <= 0:
                alpha_vel *= -1
            alpha += alpha_vel
    
            background.fill((0,0,0))
            image.set_alpha(i)
            screen.blit(image,(0,0))
            pygame.display.flip()
    
            pygame.time.delay(20)
    

提交回复
热议问题