이기거나 지거나
Coddy Pygame 여정의 게임 루프 섹션에 포함된 레슨. 32개 중 29번째.
게임이 끝납니다. 여기서는 목숨이 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)의 가운데에 표시하세요.
직접 해보기
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 플레이그라운드