왜 PyGame에 아무것도 그려지지 않습니까?
나는 파이 게임을 사용하여 파이썬에서 새 프로젝트를 시작했으며 배경은 아래쪽 절반은 회색으로, 위쪽은 검정색으로 채워야합니다. 이전에 프로젝트에서 사각형 그리기를 사용했지만 어떤 이유로 인해 깨진 것 같습니까? 내가 뭘 잘못하고 있는지 모르겠어요. 가장 이상한 점은 프로그램을 실행할 때마다 결과가 다르다는 것입니다. 때로는 검은 색 화면 만 있고 때로는 회색 직사각형이 화면의 일부를 덮지 만 화면의 절반은 가리지 않습니다.
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAY=pygame.display.set_mode((800,800))
pygame.display.set_caption("thing")
pygame.draw.rect(DISPLAY, (200,200,200), pygame.Rect(0,400,800,400))
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
답변
디스플레이를 업데이트해야합니다. 실제로 Surface물체에 그림을 그리고 있습니다. PyGame 디스플레이에 연결된 Surface 에 그리면 디스플레이에 즉시 표시되지 않습니다. 표시가 pygame.display.update()또는 로 업데이트되면 변경 사항이 표시됩니다 pygame.display.flip().
참조 pygame.display.flip():
그러면 전체 디스플레이의 내용이 업데이트됩니다.
pygame.display.flip()
전체 디스플레이의 내용을 업데이트하는 동안 pygame.display.update()
전체 영역이 아닌 화면의 일부만 업데이트 할 수 있습니다. 소프트웨어 디스플레이 용 pygame.display.update()
으로 최적화 된 버전 pygame.display.flip()
이지만 하드웨어 가속 디스플레이에서는 작동하지 않습니다.
일반적인 PyGame 애플리케이션 루프는 다음을 수행해야합니다.
- pygame.event.pump()또는로 이벤트를 처리합니다 pygame.event.get().
- 입력 이벤트 및 시간 (각각 프레임)에 따라 게임 상태 및 개체 위치 업데이트
- 전체 디스플레이를 지우거나 배경을 그립니다.
- 전체 장면 그리기 (모든 개체 그리기)
- 에 의해 디스플레이를 업데이트하거나 pygame.display.update()또는pygame.display.flip()
import pygame
from pygame.locals import *
pygame.init()
DISPLAY = pygame.display.set_mode((800,800))
pygame.display.set_caption("thing")
clock = pygame.time.Clock()
run = True
while run:
clock.tick(60)
# handle events
for event in pygame.event.get():
if event.type == QUIT:
run = False
# clear display
DISPLAY.fill(0)
# draw scene
pygame.draw.rect(DISPLAY, (200,200,200), pygame.Rect(0,400,800,400))
# update display
pygame.display.flip()
pygame.quit()
exit()