기사
Coddy의 Pygame 프로젝트: 성채를 지켜라 코스 레슨. 20개 중 2번째.
기사는 스프라이트입니다. pygame.sprite.Sprite를 기반으로 만든 클래스로, 그림은 self.image에, 위치는 self.rect에 저장합니다.
class Knight(pygame.sprite.Sprite):
def __init__(self):
super().__init__()
self.image = knight_img
self.rect = pygame.Rect(0, 0, 24, 24)
self.rect.center = courtyard.center그림은 한 변이 48픽셀이지만 Rect의 크기는 24픽셀에 불과합니다. 몬스터와 충돌하는 것은 Rect이므로, 몬스터는 기사 주변의 빈 공간 모서리가 아니라 기사의 몸에 닿아야 합니다. 작은 히트박스는 플레이어에게 공정하게 느껴집니다.
그림과 Rect의 크기가 다르므로, 그림을 Rect의 중심에 맞춰 그리세요. image.get_rect(center=point)는 한 점을 중심으로 하는 그림 크기의 Rect를 반환하며, blit은 이를 그릴 위치로 사용할 수 있습니다.
def draw(image, center):
screen.blit(image, image.get_rect(center=center))챌린지
쉬움- 기사의 그림을 불러오세요:
knight_img = load("knight.png"). - 위에
Knight클래스를 작성하세요. 그림은knight_img이고,courtyard.center를 중심으로 하는 24×24rect를 사용하세요. draw(image, center)함수를 작성하세요.- 루프 앞에서
knight = Knight()를 만들고, 배경을 그린 다음draw(knight.image, knight.rect.center)로 기사를 그리세요.
직접 해보기
import pygame
WIDTH, HEIGHT = 720, 480
TILE = 48
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Hold the Keep")
clock = pygame.time.Clock()
def load(name):
return pygame.image.load("assets/images/" + name).convert_alpha()
floor_img = load("floor.png")
wall_img = load("wall.png")
courtyard = pygame.Rect(TILE, TILE, WIDTH - 2 * TILE, HEIGHT - 2 * TILE)
background = pygame.Surface((WIDTH, HEIGHT))
for row in range(HEIGHT // TILE):
for col in range(WIDTH // TILE):
x = col * TILE
y = row * TILE
if courtyard.collidepoint(x, y):
background.blit(floor_img, (x, y))
else:
background.blit(wall_img, (x, y))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.blit(background, (0, 0))
pygame.display.flip()
clock.tick(60)
pygame.quit()
Pygame 프로젝트: 성채를 지켜라의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드