이미지가 있는 객체
Coddy Pygame 여정의 스프라이트와 이미지 섹션에 포함된 레슨. 36개 중 14번째.
적은 Rect 위에서 움직이는 이미지이며, 시작 코드는 수동으로 세 개의 Rect와 세 번의 blit을 유지합니다. 클래스는 이미지와 Rect를 함께 담을 수 있습니다.
class Enemy:
def __init__(self, image, x, y):
self.image = image
self.rect = image.get_rect(center=(x, y))
self.speed = 2
def update(self):
self.rect.y += self.speed
if self.rect.top > 480:
self.rect.bottom = 0
def draw(self, screen):
screen.blit(self.image, self.rect)이미지는 전달받으며, __init__에서 불러오지 않습니다. 각 파일을 맨 위에서 한 번씩 불러오고, 해당 이미지를 사용하는 모든 적에게 같은 Surface를 전달하세요. 빨간 적이 열 마리라면 모두 같은 빨간 이미지를 공유합니다. 하지만 각 적은 자기만의 Rect를 가지므로 각자 따로 움직입니다.
적을 움직이는 것은 Rect를 움직이는 것이고, 적을 그리는 것은 Rect 위치에 이미지를 blit하는 것입니다. 이 섹션의 모든 게임 객체가 갖는 두 속성입니다.
챌린지
중급- 위와 같이
Enemy클래스를 작성하고,__init__(self, image, x, y),update(self),draw(self, screen)을 구현하세요. Rect는 (x, y)를 중심으로 하고, 프레임마다 2픽셀씩 아래로 이동하며, 창 아래로 내려가면 위쪽 가장자리 위로 돌아오게 하세요. enemies를 세 개의 적이 담긴 목록으로 만드세요. 빨간 적은 (160, 100), 초록 적은 (320, 100), 노란 적은 (480, 100)을 중심으로 배치하세요.- 목록에 있는 모든 적을 업데이트하고 그리세요. 세 개의 Rect는 제거하세요.
직접 해보기
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Enemy Rain")
clock = pygame.time.Clock()
red = pygame.image.load("assets/images/enemy_red.png").convert_alpha()
green = pygame.image.load("assets/images/enemy_green.png").convert_alpha()
yellow = pygame.image.load("assets/images/enemy_yellow.png").convert_alpha()
red_rect = red.get_rect(center=(160, 100))
green_rect = green.get_rect(center=(320, 100))
yellow_rect = yellow.get_rect(center=(480, 100))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
for rect in (red_rect, green_rect, yellow_rect):
rect.y += 2
if rect.top > 480:
rect.bottom = 0
screen.fill((20, 22, 40))
screen.blit(red, red_rect)
screen.blit(green, green_rect)
screen.blit(yellow, yellow_rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()
스프라이트와 이미지의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드