【问题标题】:Why is the PyGame animation is flickering为什么 PyGame 动画闪烁
【发布时间】:2020-09-19 01:48:15
【问题描述】:

所以我运行代码,它开始出现故障。我是 pygame 的新手。

代码如下:

import pygame

pygame.init()
# Screen (Pixels by Pixels (X and Y (X = right and left Y = up and down)))
screen = pygame.display.set_mode((1000, 1000))
running = True
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Icon.png')
pygame.display.set_icon(icon)
# Player Icon/Image
playerimg = pygame.image.load('Player.png')
playerX = 370
playerY = 480

def player(x, y):
    # Blit means Draw
    screen.blit(playerimg, (x, y))


# Game loop (Put all code for pygame in this loop)
while running:
    screen.fill((225, 0, 0))
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # if keystroke is pressed check whether is right or left
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                print("Left arrow is pressed")

            if event.key == pygame.K_RIGHT:
                print("Right key has been pressed")


            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                print("kEYSTROKE RELEASED")

    # RGB (screen.fill) = red green blue

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

图片不是故障图片,因为我无法发布视频,但这是我的代码所做的

【问题讨论】:

    标签: python pygame pycharm


    【解决方案1】:

    问题是由多次调用pygame.display.update() 引起的。在应用程序循环结束时更新显示就足够了。多次调用pygame.display.update()pygame.display.flip() 会导致闪烁。

    从您的代码中删除对pygame.display.update() 的所有调用,但在应用程序循环结束时调用一次:

    while running:
        screen.fill((225, 0, 0))
        # pygame.display.update() <---- DELETE
    
        # [...]
    
        player(playerX, playerY)
        pygame.display.update()
    

    如果您在screen.fill() 之后更新显示,则显示会在短时间内填充背景颜色。然后播放器被绘制 (blit) 并显示播放器在背景之上。

    【讨论】:

    • @piddi24 enemy 这个名字是函数的名字,不是表面的名字。它必须是 screen.blit(enemyimg, (x, y)) 而不是 screen.blit(enemy, (x, y))
    猜你喜欢
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 2012-03-11
    • 1970-01-01
    相关资源
    最近更新 更多