为什么 PyGame 动画闪烁
- 2025-01-21 09:02:00
- admin 原创
- 88
问题描述:
所以我运行代码,它就开始出现故障。我是 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()
由于我无法发布视频,所以图片不是故障图片,而是我的代码导致的
解决方案 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
),并且显示播放器位于背景之上。
相关推荐
热门文章
项目管理软件有哪些?
热门标签
云禅道AD