如何解决未绘制矩形
运行此代码时:
import pygame,time
GREEN = (30,156,38)
WHITE = (255,255,255)
pygame.init()
screen = pygame.display.set_mode((640,480))
screen.fill(WHITE)
pygame.draw.rect(screen,GREEN,(0,100,100))
time.sleep(3)
Pygame 显示黑屏 3 秒,但不绘制矩形。
我正在使用 Atom 使用 script
包运行代码
解决方法
您必须实现一个应用程序循环。典型的 PyGame 应用程序循环必须:
- 通过
pygame.event.pump()
或pygame.event.get()
处理事件。 - 根据输入事件和时间(分别为帧)更新游戏状态和对象位置
- 清除整个显示或绘制背景
- 绘制整个场景(
blit
所有对象) - 通过
pygame.display.update()
或pygame.display.flip()
更新显示 - 限制每秒帧数以限制 CPU 使用率
import pygame
GREEN = (30,156,38)
WHITE = (255,255,255)
pygame.init()
screen = pygame.display.set_mode((640,480))
clock = pygame.time.Clock()
# applicaition loop
run = True
while run:
# limit frames per second
clock.tick(60)
# event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# clear display
screen.fill(WHITE)
# draw objects
pygame.draw.rect(screen,GREEN,(0,100,100))
# update display
pygame.display.flip()
pygame.quit()
exit()
注意,您必须进行事件处理。分别见pygame.event.get()
pygame.event.pump()
:
对于游戏的每一帧,您都需要对事件队列进行某种调用。这可确保您的程序可以在内部与操作系统的其余部分进行交互。
,您必须更新屏幕like that:
pygame.display.flip()
渲染您刚刚绘制的内容。
您的代码应如下所示:
import pygame
import time
pygame.init()
GREEN = (30,255)
screen = pygame.display.set_mode((640,480))
# draw on screen
screen.fill(WHITE)
pygame.draw.rect(screen,100))
# show that to the user
pygame.display.flip()
time.sleep(3)
离题:您还应该get the events允许用户关闭窗口:
import pygame
from pygame.locals import QUIT
import time
pygame.init()
GREEN = (30,480))
clock = pygame.time.Clock() # to slow down the code to a given FPS
# draw on screen
screen.fill(WHITE)
pygame.draw.rect(screen,100))
# show that to the user
pygame.display.flip()
start_counter = time.time()
while time.time() - start_counter < 3: # wait for 3 seconds to elapse
for event in pygame.event.get(): # get the events
if event.type == QUIT: # if the user clicks "X"
exit() # quit pygame and exit the program
clock.tick(10) # limit to 10 FPS
# (no animation,you don't have to have a great framerate)
请注意,如果您想像经典游戏一样重复它,您必须将所有这些放入 game loop 中。
,更新屏幕:
pygame.display.update()
在您发布的代码末尾。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。