循环通过两个图像的模块由键盘命令切换



我正在尝试构建一个模块,该模块在按下键时通过两个或多个图像循环并在抬高键时停止循环。不幸的是,一旦我得到图像开始循环,它们就不会停止。请帮助,我正在用Python 2.7和Pygame编程。这是我的评论代码。

import pygame, sys 
running = True
run = False
pygame.init()
screen = pygame.display.set_mode([640,480]) #Initializes pygame window
screen.fill([255, 255, 255]) #Fills screen with white
picture = pygame.image.load('picture1.png') #Loads image 1
picturetwo = pygame.image.load('picture2.png') #Loads image 2
screen.blit(picture, [50, 50])
import pygame, sys 
running = True
run = False
pygame.init()
screen = pygame.display.set_mode([640,480]) #Initializes pygame window
screen.fill([255, 255, 255]) #Fills screen with white
picture = pygame.image.load('picture1.png') #Loads image 1
picturetwo = pygame.image.load('picture2.png') #Loads image 2
screen.blit(picture, [50, 50])
#Places picture in window. 50 pixels down from the top and 50 pixels right from the top
pygame.display.flip()
while running:
    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
        #If a key is pressed                #If that key is the right arrow
            run = True
        while run == True:
            pygame.time.delay(500)
            pygame.draw.rect(screen, [255,255,255], [50, 50, 150, 150], 0)
            #Creates a white rectangle to fill over the preceding image
            screen.blit(picturetwo, [50, 50])
            #Loads the second image over the first rectangle
            pygame.display.flip()
            #Repeats
            pygame.time.delay(500)
            pygame.draw.rect(screen, [255,255,255], [50, 50, 150, 150], 0)
            screen.blit(picture, [50, 50])
            pygame.display.flip()
            if event.key != pygame.K_RIGHT:
#If the right key is not pressed, exits loop. DOES NOT WORK
                run = False
        if event.type == pygame.QUIT: #Exits program
            running = False
pygame.quit()

您正在使用事件KEYDOWN检查是否按下键。它无法正常工作。当您仅按键时,就会发出活动。请参阅此帖子以获取更详细的说明。

要检查是否按下键,请使用:

pressed = pygame.key.get_pressed()
if pressed[pygame.K_RIGHT]: #or the constant corresponding to the key to check 
    #do things to do when that key is pressed.

您可以尝试以这种方式重写while循环:

while running:
    #check the incoming events, just to check when to quit
    for event in pygame.event.get():
        if event.type == pygame.QUIT: #Exits program
            running = False
    pressed = pygame.key.get_pressed()
    if pressed[K_RIGHT]:
        pygame.time.delay(500)
        pygame.draw.rect(screen, [255,255,255], [50, 50, 150, 150], 0)
        #Creates a white rectangle to fill over the preceding image
        screen.blit(picturetwo, [50, 50])
        #Loads the second image over the first rectangle
        pygame.display.flip()
        #Repeats
        pygame.time.delay(500)
        pygame.draw.rect(screen, [255,255,255], [50, 50, 150, 150], 0)
        screen.blit(picture, [50, 50])
        pygame.display.flip()

最新更新