Menu
CoddyTech

장애물

Coddy Pygame 여정의 게임 규칙 섹션에 포함된 레슨. 30개 중 26번째.

이제 뛰어넘을 것이 필요합니다. 장애물은 오른쪽 가장자리에서 조금 떨어진 지점의 땅 위에서 시작해 왼쪽으로 움직이는 스프라이트입니다:

class Obstacle(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = random.choice(obstacle_images)
        self.rect = self.image.get_rect(midbottom=(664, GROUND_Y))

    def update(self):
        self.rect.x -= speed
        if self.rect.right < 0:
            self.kill()

obstacle_images에는 한 번 불러온 가시 공과 덩어리 이미지가 들어 있으므로, 각 장애물은 파일을 읽지 않고 그림을 선택합니다. kill()은 스프라이트가 속한 모든 그룹에서 스프라이트를 제거하므로, 왼쪽으로 사라진 장애물은 잊힙니다.

장애물은 그룹에 넣어 둡니다. obstacles.update()는 장애물을 모두 움직이고 obstacles.draw(screen)은 모두 그립니다. 타이머가 장애물을 추가합니다. 타이머가 작동할 때마다 무작위 간격으로 다시 설정해 플레이어가 일정한 리듬으로 점프할 수 없게 합니다:

if event.type == SPAWN:
    obstacles.add(Obstacle())
    pygame.time.set_timer(SPAWN, random.randint(1000, 2000))

아직 러너는 장애물에 부딪히지 않습니다. 그건 다음에 다룹니다.

challenge icon

챌린지

중급

주자 쪽으로 장애물을 보내세요.

  1. SPAWN = pygame.USEREVENT + 1, speed = 6 및 obstacle_images를 추가하세요: spike_ball.png와 blob.png.
  2. 표시된 Obstacle 스프라이트와 obstacles 그룹을 작성하세요.
  3. SPAWN 타이머를 1500 ms로 시작하세요. SPAWN이 발생하면 장애물을 추가하고 random.randint(1000, 2000)으로 타이머를 다시 시작하세요.
  4. 매 프레임 그룹을 업데이트하고 그리세요.

‘플레이’를 누르세요. 장애물이 오른쪽에서 들어옵니다. 그런 다음 ‘확인’을 누르세요.

직접 해보기

import pygame

pygame.init()
screen = pygame.display.set_mode((640, 320))
pygame.display.set_caption("Sky Runner")
clock = pygame.time.Clock()

SKY = (140, 200, 240)
GROUND = (90, 160, 80)
GROUND_Y = 260
GRAVITY = 1


class Runner(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.frames = [
            pygame.image.load("assets/images/player.png").convert_alpha(),
            pygame.image.load("assets/images/player_walk.png").convert_alpha(),
        ]
        self.image = self.frames[0]
        self.step = 0
        self.rect = self.image.get_rect(midbottom=(100, GROUND_Y))
        self.vy = 0

    def jump(self):
        if self.rect.bottom == GROUND_Y:
            self.vy = -16

    def update(self):
        self.vy += GRAVITY
        self.rect.y += self.vy
        if self.rect.bottom >= GROUND_Y:
            self.rect.bottom = GROUND_Y
            self.vy = 0
        if self.rect.bottom == GROUND_Y:
            self.step += 1
            self.image = self.frames[self.step // 8 % 2]
        else:
            self.image = self.frames[1]


runner = Runner()

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN and event.key in (pygame.K_SPACE, pygame.K_UP):
            runner.jump()

    runner.update()

    screen.fill(SKY)
    pygame.draw.rect(screen, GROUND, (0, GROUND_Y, 640, 60))
    screen.blit(runner.image, runner.rect)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

게임 규칙의 모든 레슨

직접 연습해 보세요: Pygame 플레이그라운드