首页 > 解决方案 > 仅在将鼠标移到屏幕上时才更新屏幕,我的代码有问题吗?

问题描述

这是代码:

# Initialize the pygame
pygame.init()


# Create the screen
screen = pygame.display.set_mode((800, 600))


# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)


# Player
playerImg = pygame.image.load("player.png")
playerX = 370
playerY = 480


def player(x, y):
    screen.blit(playerImg, (x, y))


# Run game until x is pressed

running = True

while running:
    for event in pygame.event.get():

        screen.fill((0, 0, 0))
        playerX += 0.1
        print(playerX)

        if event.type == pygame.QUIT:
            running = False
            pygame.display.quit()
            sys.exit()

        player(playerX, playerY)
        pygame.display.update()

出于某种原因,只有当我将鼠标移到屏幕上或我在键盘上发送垃圾邮件时,屏幕才会更新。我没有更多细节要添加,所以我必须输入这个,否则我无法发布我的问题。

标签: pythonpygame

解决方案


修正你的缩进。您只需要在事件循环中检查事件类型。绘制代码在while循环下。

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
            pygame.display.quit()
            sys.exit()

    screen.fill((0, 0, 0))
    playerX += 0.1
    print(playerX)
    
    player(playerX, playerY)
    pygame.display.update()

推荐阅读