python - 仅在将鼠标移到屏幕上时才更新屏幕,我的代码有问题吗?
问题描述
这是代码:
# 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()
出于某种原因,只有当我将鼠标移到屏幕上或我在键盘上发送垃圾邮件时,屏幕才会更新。我没有更多细节要添加,所以我必须输入这个,否则我无法发布我的问题。
解决方案
修正你的缩进。您只需要在事件循环中检查事件类型。绘制代码在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()
推荐阅读
- scala - 关于使用 Scala 创建 jar 文件时出现 org.apache.spark.sql.AnalysisException 错误
- swift - 在 iOS 上从本地领域数据库中删除多个对象
- syntax - Oracle BI Publisher 程序调用
- algorithm - 有效地计算非常大的数字(如 10**20)的所有完美平方数
- javascript - 如何为谷歌地图 setMarkers 函数中的所有图标变量添加统一大小?
- java - 放心使用 Hamcrest-Date 和 DateTimeFormatter
- asp-classic - 如何使用 Visual Studio 调试经典 ASP
- php - 如何在数组中添加if语句
- javascript - .then() 回调中的“return”是从内部范围还是外部范围返回?
- apache-camel - Camel 3.x:禁用路线的自动注册