import pygame, sys from pygame.locals import * pygame.init() FPS = 30 # frames per second setting fpsClock = pygame.time.Clock() # set up the window DISPLAYSURF = pygame.display.set_mode((400, 300), 0, 32) pygame.display.set_caption('Animation') WHITE = (255, 255, 255) catImg = pygame.image.load('cat.png') catx = 10 caty = 10 direction = 'right' while True: # the main game loop DISPLAYSURF.fill(WHITE) if direction == 'right': catx += 5 if catx == 280: direction = 'down' elif direction == 'down': caty += 5 if caty == 220: direction = 'left' elif direction == 'left': catx -= 5 if catx == 10: direction = 'up' elif direction == 'up': caty -= 5 if caty == 10: direction = 'right' DISPLAYSURF.blit(catImg, (catx, caty)) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update() #fpsClock.tick(FPS)
다음과 같은 코드를 실행하면 흰 화면에 고양이가 돌아다니는 모습을 볼 수 있다.
pygame.time.Clock()을 이용해 clock(fpsClock)을 만들어준 후, fpsClock.tick(FPS)를 pygame.display.update() 뒤에 배치해 애니메이션의 속도를 조절한다.
FPS가 낮을수록 프로그램은 느리게 진행되며, 높을수록 프로그램은 빠르게 진행된다.
* (clock_name).tick()이 없는 경우, 파이썬 프로그램은 있는 힘껏 프로그램을 진행시킨다. 직접 뺀 채로 컴파일 해보는 것을 추천한다.
pygame.image.load()를 이용해 사진 파일을 불러와서 변수에 저장한 후, 다른 함수를 이용할 수 있다.
불러오려는 파일은 AppData 폴더 속 Python 폴더에 있거나, 실행 코드 파일과 같은 폴더 내에 있어야 한다. 그렇지 않은 경우 에러가 발생한다.
DISPLAYSURF.blit(catImg, (catx, caty))
blit() 함수를 이용하여 catImg를 DISPLAYSURF 위에 복사했다.
blit() 함수는 두개의 인자를 받는데, 첫 번째는 복사할 객체이고, 두 번째는 객체를 복사할 위치의 좌표이다.
감사합니다
답글삭제