为什么我的形象被遮盖了?

时间:2017-08-06 22:36:44

标签: python image pygame

我开始观看有关通过sentdex学习pygame的youtube视频系列。 我一直在遵循他所有的步骤,我到了我有车(图像)的地方,它在白色的屏幕上。但是,当我放入能够移动汽车的功能时。下次我跑它时,我看不到我的车。我注意到,当我关闭屏幕时,我可以看到它一瞬间。我试着用我想到的每一种方式搜索这个问题。这对我来说可能是一个小小的愚蠢错误。先感谢您     导入pygame

pygame.init()

display_width = 800
display_height = 600

black = (0,0,0)
white = (255,255,255)


gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()

carImg = pygame.image.load('racecar.png')

def car(x, y):
    gameDisplay.blit(carImg,(x,y))


x = (display_width * 0.45)
y = (display_height * 0.6)

x_change = 0

crashed = False

while not crashed:

for event in pygame.event.get():
    if event.type == pygame.QUIT:
    crashed = True

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_LEFT:
        x_change = -5
    if event.key == pygame.K_RIGHT:
        x_change = 5

if event.type == pygame.KEYUP:
    if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
        x_change = 0

x += x_change             

gameDisplay.fill(white)           
car(x,y)
pygame.display.update()
clock.tick(60)

pygame.quit()
quit()

1 个答案:

答案 0 :(得分:0)

你的缩进搞砸了。从for event in pygame.event.get():clock.tick(60)的所有内容都应缩进,以表明它适合while not crashed:循环。此外,crashed = True应缩进以显示它在if event.type == pygame.QUIT:语句中。此外,pygame.KEYDOWNpygame.KEYUP比较应位于for event in pygame.event.get():循环内。最后,您可以通过将某些if更改为elif来提高速度。这是代码最后一部分的更正版本:

while not crashed:

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True

        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                x_change = -5
            elif event.key == pygame.K_RIGHT:
                x_change = 5

        elif event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                x_change = 0

    x += x_change             

    gameDisplay.fill(white)           
    car(x, y)
    pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()