시간이 지날수록 더 빠르게
Coddy의 Pygame으로 게임 만들기 코스 레슨. 40개 중 18번째.
게임이 진행될수록 더 어려워집니다. 여기서는 블록이 10초마다 조금씩 더 빠르게 떨어집니다.
pygame.time.set_timer(event_type, ms)는 ms밀리초마다 해당 유형의 이벤트를 게시합니다. pygame.USEREVENT를 사용해 직접 이벤트 유형을 만드세요. 이 값은 pygame이 여러분이 사용할 수 있도록 비워 둔 숫자입니다.
SPEED_UP = pygame.USEREVENT + 1
pygame.time.set_timer(SPEED_UP, 10000)
fall_speed = 3
for event in pygame.event.get():
if event.type == SPEED_UP:
fall_speed += 1이벤트는 다른 이벤트들과 함께 이벤트 루프에 10초마다 한 번씩 도착합니다. 그러면 블록은 고정된 3 대신 block.y += fall_speed를 사용해 떨어집니다. 새 게임은 다시 느린 속도로 시작하므로, 다시 시작할 때도 fall_speed = 3으로 설정합니다.
챌린지
중급- 글꼴 아래에
SPEED_UP = pygame.USEREVENT + 1을 만들고, 10000 ms마다 해당 이벤트가 발생하도록 타이머를 시작하세요. - 루프 전에
fall_speed = 3으로 설정하고 낙하에 이 값을 사용하세요. - SPEED_UP 이벤트가 도착하면
fall_speed에 1을 더하세요. - R 키로 새 게임을 시작할 때 값을 다시 3으로 설정하세요.
직접 해보기
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)
score = 0
lives = 3
paused = False
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_p:
paused = not paused
elif event.key == pygame.K_r and (lives == 0 or score == 10):
score = 0
lives = 3
basket.x = 200
block.y = -20
block.x = random.randint(0, 460)
if lives > 0 and score < 10 and not paused:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
basket.x -= 8
if keys[pygame.K_RIGHT]:
basket.x += 8
basket.clamp_ip(screen.get_rect())
block.y += 3
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
lives -= 1
if block.colliderect(basket):
block.y = -20
block.x = random.randint(0, 460)
score += 1
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), basket)
pygame.draw.rect(screen, (235, 80, 80), block)
score_text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(score_text, (10, 10))
lives_text = font.render(f"Lives: {lives}", True, (240, 240, 240))
screen.blit(lives_text, (370, 10))
if lives == 0:
message = font.render("Game over", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))
elif score == 10:
message = font.render("You win!", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))
if lives == 0 or score == 10:
again = font.render("Press R to play again", True, (240, 240, 240))
screen.blit(again, again.get_rect(center=(240, 200)))
if paused:
message = font.render("Paused", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Pygame으로 게임 만들기의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드