Skip to main content
 首页 » 编程设计

python之带有鼠标事件的 Pygame blit 图像

2024年09月07日17yjmyzz

我在此代码中使用了 Pygame。这就像一个游戏,当用户点击鼠标按钮时,鼠标位置会出现一个激光图像,该图像会上升,并最终离开屏幕。当用户点击鼠标按钮时,我试图 blit 图像。我正在使用的这段代码不起作用,我不知道为什么。我的问题从主 for 循环开始

    import pygame 
 
    # Initialize Pygame 
    pygame.init() 
 
    #___GLOBAL CONSTANTS___ 
    # Define some colors 
    BLACK = (0, 0, 0) 
    WHITE = (255, 255, 255) 
    GREEN = (0, 255, 0) 
    RED = (255, 0, 0) 
 
 
    # Set the height and width of the screen 
    screen_width = 500 
    screen_height = 500 
    screen = pygame.display.set_mode([screen_width, screen_height]) 
 
 
    #Load Laser image of spaceship 
    laser_image = pygame.image.load('laserRed16.png').convert() 
 
 
    #Load sound music 
    sound = pygame.mixer.Sound('laser5.ogg') 
 
 
    # Loop until the user clicks the close button. 
    done = False 
 
    # Used to manage how fast the screen updates 
    clock = pygame.time.Clock() 
 
 
    # -------- Main Program Loop ----------- 
    while not done: 
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT: 
                done = True 
            elif event.type == pygame.MOUSEBUTTONDOWN: 
                # Get the current mouse position. This returns the position 
                # as a list of two numbers. 
                sound.play() 
                #Get the mouse position  
                mouse_position = pygame.mouse.get_pos() 
                mouse_x = mouse_position[0] 
                mouse_y = mouse_position[1] 
                # Set the laser image when the spaceship fires 
                for i in range(50): 
                    screen.blit(laser_image,[mouse_x + laser_x_vector,mouse_y + laser_x_vector]) 
                    laser_x_vector += 2 
                    laser_x_vector += 2 
 
 
        # Clear the screen 
        screen.fill(WHITE) 
 
        #Limit to 20 sec 
        clock.tick(20) 
 
        # Go ahead and update the screen with what we've drawn. 
        pygame.display.flip() 
pygame.quit() 

请您参考如下方法:

在你 blit the lazer 之后你填满了屏幕,所以 lazer 不会出现。你应该在你 blit the lazer 之前填充,这样 lazer 就会出现。