Why is the PyGame animation is flickering(为什么 PyGame 动画闪烁)
问题描述
所以我运行代码,它开始出现故障.我是 pygame 的新手.
So I run the code and it just starts glitching out. I am new to 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()
图片不是故障图片,因为我无法发布视频,但这是我的代码所做的
The image is not the glitching one as I was not able to post a video but it is what my code does
推荐答案
问题是多次调用pygame.display.update()
.在应用程序循环结束时更新显示就足够了.多次调用 pygame.display.update()
或 pygame.display.flip()
会导致闪烁.
The problem is caused by multiple calls to pygame.display.update()
. An update of the display at the end of the application loop is sufficient. Multiple calls to pygame.display.update()
or pygame.display.flip()
cause flickering.
从您的代码中删除对 pygame.display.update()
的所有调用,但在应用程序循环结束时调用一次:
Remove all calls to pygame.display.update()
from your code, but call it once at the end of the application loop:
while running:
screen.fill((225, 0, 0))
# pygame.display.update() <---- DELETE
# [...]
player(playerX, playerY)
pygame.display.update()
如果您在 screen.fill()
之后更新显示,显示将在短时间内被背景色填充.然后播放器被绘制 (blit
) 并显示播放器在背景之上.
If you update the display after screen.fill()
, the display will be shown filled with the background color for a short moment. Then the player is drawn (blit
) and the display is shown with the player on top of the background.
这篇关于为什么 PyGame 动画闪烁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 PyGame 动画闪烁
基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01