python - 为什么我的 pygame 寡妇在关闭前只保持打开一秒钟?
问题描述
我目前正在关注 YouTube 上的初学者 pygame 教程,但即使我完全从教程中复制了代码,我的 pygame 窗口也只会保持打开大约一秒钟然后关闭。
注意:大约三年前有人在这里问过这个问题,但它并没有解决我的问题。我的代码在下面
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('hello world')
解决方案
您的脚本即将结束,因此pygame
关闭了所有内容。
您必须创建一个循环才能让您的游戏继续运行,并带有退出循环的条件。
您还需要初始化显示pygame.display.init()
import pygame
pygame.init()
pygame.display.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('hello world')
clock = pygame.time.Clock()
FPS = 60 # Frames per second.
# Some shortcuts for colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
# For example, display a white rect
rect = pygame.Rect((0, 0), (32, 32))
image = pygame.Surface((32, 32))
image.fill(WHITE)
# Game loop
while True:
# Ensure game runs at a constant speed
clock.tick(FPS)
# 1. Handle events
for event in pygame.event.get():
# User pressed the close button ?
if event.type == pygame.QUIT:
quit()
# Close the program. Other methods like 'raise SystemExit' or 'sys.exit()'.
# Calling 'pygame.quit()' won't close the program! It will just uninitialize the modules.
# 2. Put updates to the game logic here
# 3. Render
win.fill(BLACK) # first clear the screen
win.blit(image, rect) # draw whatever you need
pygame.display.flip() # copy to the screen
推荐阅读
- java - 我在 sleep() 时中断了方法并且没有异常
- kotlin - 返回包含特定列表类型作为参数的列表的扩展函数
- algorithm - 如何修剪这种类型的排序加权树以最大化这个特定的功能?
- react-native - 试图更新高位图表数据
- python - 在 tkinter 中生成一个带有按钮的新列表,其中包含稍后使用的变量错误 python tkinter
- html - Angular ngFor 索引序列号
- sql - 如何在 HIVe 中为 IN 子句提供参数
- jenkins - 如何将 Jenkins Ivy 项目转换为 Freestyle 项目?
- javascript - 本地存储不保留值
- python - 如何在 Python 中将零向量或矩阵添加到 3D 数组