이기거나 지거나
Coddy의 Pygame으로 게임 만들기 코스 레슨. 41개 중 15번째.
게임이 끝납니다. 여기서는 생명이 0이 되면 지고 점수가 10이 되면 이깁니다. 어느 쪽도 아직 일어나지 않았다면 게임은 진행 중입니다.
움직이는 모든 것을 하나의 조건 안에 넣어 게임이 끝나면 멈추게 하세요.
if lives > 0 and score < 10:
# 키, 바구니, 블록, 잡기와 놓치기그 if문 바깥에서 그리기는 계속됩니다. 화면에는 마지막 프레임이 그대로 표시되고, 그 위에 결과가 표시됩니다.
if lives == 0:
message = font.render("Game over", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))message.get_rect(center=(240, 160))는 텍스트 이미지의 가운데를 (240, 160)에 놓았을 때의 Rect입니다. Rect를 기준으로 블리팅할 때는 왼쪽 위 모서리를 사용하므로 텍스트가 가운데에 배치됩니다.
챌린지
중급승리하거나 패배하면 게임을 끝내세요.
- 움직이는 모든 항목(키, 바구니, 블록, 잡기와 놓치기)을
if lives > 0 and score < 10:아래에 들여쓰기하세요. - 점수와 생명 수를 표시한 다음,
lives == 0일 때는Game over를,score == 10일 때는You win!을(240, 160)위치에 가운데 정렬하여 표시하세요.
‘플레이’를 누르고 블록 세 개를 놓치세요. Game over가 표시되고 게임이 멈춥니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
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))
pygame.display.flip()
clock.tick(60)
pygame.quit()
Pygame으로 게임 만들기의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드