메서드
Coddy Pygame 여정의 스프라이트와 이미지 섹션에 포함된 레슨. 36개 중 11번째.
이제 별의 숫자 값은 클래스 안에 있지만, 별이 어떻게 떨어지고 어떻게 그려지는지에 관한 규칙은 여전히 반복문 안에 있습니다. 클래스 안에 작성한 함수는 메서드이며, 데이터와 규칙을 한곳에 둡니다:
class Star:
# __init__는 이전과 동일
def update(self):
self.y += self.speed
if self.y > 480:
self.y = 0
def draw(self, screen):
pygame.draw.circle(screen, (255, 255, 255), (self.x, self.y), 4)각 메서드의 첫 번째 매개변수는 메서드가 작동하는 객체인 self입니다. 점을 사용해 객체의 메서드를 호출하며, pygame의 Surface는 다른 인수와 마찬가지로 전달합니다:
star.update()
star.draw(screen)이제 메인 반복문은 한 프레임에서 일어나는 일을 그대로 나타냅니다. 별을 업데이트한 다음 그립니다. pygame 프로그램의 게임 객체에는 거의 항상 이 두 메서드인 update와 draw가 있습니다.
챌린지
중급Star에 메서드update(self)를 추가합니다.self.speed를self.y에 더하고,self.y가 480을 초과하면 별을y = 0으로 되돌립니다.draw(self, screen)을 추가합니다.(self.x, self.y)위치에 반지름이 4인 흰색 원을 그립니다.- 반복문에서
star.update()를 호출하고, 화면을 채운 다음star.draw(screen)를 호출합니다.
직접 해보기
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Falling Star")
clock = pygame.time.Clock()
class Star:
def __init__(self, x, y):
self.x = x
self.y = y
self.speed = 2
star = Star(320, 0)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
star.y += star.speed
if star.y > 480:
star.y = 0
screen.fill((20, 22, 40))
pygame.draw.circle(screen, (255, 255, 255), (star.x, star.y), 4)
pygame.display.flip()
clock.tick(60)
pygame.quit()
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
스프라이트와 이미지의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드