运行此代码时:
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,0,100,100))
time.sleep(3)
Pygame 显示黑屏 3 秒,但不绘制矩形。
我正在使用 Atom 使用 script
包运行代码
答案 0 :(得分:2)
您必须实现一个应用程序循环。典型的 PyGame 应用程序循环必须:
pygame.event.pump()
或 pygame.event.get()
处理事件。blit
所有对象)pygame.display.update()
或 pygame.display.flip()
更新显示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, 0, 100, 100))
# update display
pygame.display.flip()
pygame.quit()
exit()
注意,您必须进行事件处理。分别见pygame.event.get()
pygame.event.pump()
:
对于游戏的每一帧,您都需要对事件队列进行某种调用。这可确保您的程序可以在内部与操作系统的其余部分进行交互。
答案 1 :(得分:1)
您必须更新屏幕like that:
pygame.display.flip()
渲染您刚刚绘制的内容。
您的代码应如下所示:
import pygame
import time
pygame.init()
GREEN = (30, 156, 38)
WHITE = (255,255,255)
screen = pygame.display.set_mode((640, 480))
# draw on screen
screen.fill(WHITE)
pygame.draw.rect(screen, GREEN, (0,0,100,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, 156, 38)
WHITE = (255, 255, 255)
screen = pygame.display.set_mode((640, 480))
clock = pygame.time.Clock() # to slow down the code to a given FPS
# draw on screen
screen.fill(WHITE)
pygame.draw.rect(screen, GREEN, (0, 0, 100, 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 中。
答案 2 :(得分:1)
更新屏幕:
pygame.display.update()
在您发布的代码末尾。