python - 为什么我的 PyGame 应用程序根本没有运行?
问题描述
我有一个简单的 Pygame 程序:
#!/usr/bin/env python
import pygame
from pygame.locals import *
pygame.init()
win = pygame.display.set_mode((400,400))
pygame.display.set_caption("My first game")
但是每次我尝试运行它时,我都会得到这个:
pygame 2.0.0 (SDL 2.0.12, python 3.8.3)
Hello from the pygame community. https://www.pygame.org/contribute.html
然后什么也没有发生。为什么我不能运行这个程序?
解决方案
您的应用程序运行良好。但是,您还没有实现应用程序循环:
import pygame
from pygame.locals import *
pygame.init()
win = pygame.display.set_mode((400,400))
pygame.display.set_caption("My first game")
clock = pygame.time.Clock()
run = True
while run:
# handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# update game objects
# [...]
# clear display
win.fill((0, 0, 0))
# draw game objects
# [...]
# update display
pygame.display.flip()
# limit frames per second
clock.tick(60)
pygame.quit()
典型的 PyGame 应用程序循环必须:
- 通过调用
pygame.event.pump()
或来处理事件pygame.event.get()
。 - 根据输入事件和时间(分别为帧)更新对象的游戏状态和位置
- 清除整个显示或绘制背景
- 绘制整个场景(
blit
所有对象) - 通过调用
pygame.display.update()
或更新显示pygame.display.flip()
- 限制每秒帧数以限制 CPU 使用率
pygame.time.Clock.tick
repl.it/@Rabbid76/PyGame-MinimalApplicationLoop另请参阅事件和应用程序循环
推荐阅读
- r - 加载 ggplot2 时抛出错误:包或命名空间加载失败 .... 没有名为“颜色空间”的包
- spring - 经过身份验证的用户的 Spring 安全过滤器
- libreoffice - 在单元格 B1 中使用 A1 的部分值来计算公式
- c++ - 当实例为右值时,成员函数的具体实现?
- java - 当我尝试添加到 ArrayList 时,我得到 NullPointerException
- python - python3和pip安装在mac上但是找不到pip3命令
- sql - 如何将一些数据连接到所有数据
- python - 如何在熊猫 df 中每隔一行创建新列
- reactjs - React Lifecycles 管理具有变化值的间隔
- sparql - 维基数据按人口对给定州的城市进行排序