본문 바로가기
개발/Python

PyGame 애니메이션이 깜박이는 이유

by MinorMan 2023. 8. 12.
반응형

<질문>

그래서 코드를 실행하면 오류가 발생하기 시작합니다. 저는 파이 게임을 처음 사용합니다.

코드는 다음과 같습니다.

import pygame

pygame.init()
# Screen (Pixels by Pixels (X and Y (X = right and left Y = up and down)))
screen = pygame.display.set_mode((1000, 1000))
running = True
# Title and Icon
pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('Icon.png')
pygame.display.set_icon(icon)
# Player Icon/Image
playerimg = pygame.image.load('Player.png')
playerX = 370
playerY = 480

def player(x, y):
    # Blit means Draw
    screen.blit(playerimg, (x, y))


# Game loop (Put all code for pygame in this loop)
while running:
    screen.fill((225, 0, 0))
    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # if keystroke is pressed check whether is right or left
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                print("Left arrow is pressed")

            if event.key == pygame.K_RIGHT:
                print("Right key has been pressed")


            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                print("kEYSTROKE RELEASED")

    # RGB (screen.fill) = red green blue

    player(playerX, playerY)
    pygame.display.update()

비디오를 게시할 수 없었기 때문에 이미지가 결함이 있는 것이 아니라 내 코드가 수행하는 것입니다.

enter image description here


<답변1>

문제는 다음을 여러 번 호출하여 발생합니다.pygame.display.update(). 애플리케이션 루프의 끝에서 디스플레이를 업데이트하는 것으로 충분합니다. 에 대한 다중 호출pygame.display.update()또는pygame.display.flip()깜박임을 유발합니다.

에 대한 모든 호출 제거pygame.display.update()코드에서 호출하지만 애플리케이션 루프의 끝에서 한 번만 호출합니다.

while running:
    screen.fill((225, 0, 0))
    # pygame.display.update() <---- DELETE

    # [...]

    player(playerX, playerY)
    pygame.display.update()

이후 디스플레이를 업데이트하면screen.fill(), 잠시 동안 배경색으로 채워진 디스플레이가 표시됩니다. 그런 다음 플레이어가 그려집니다(blit) 배경 위에 플레이어가 있는 디스플레이가 표시됩니다.

728x90

댓글