다시 플레이하기
Coddy의 Pygame으로 게임 만들기 코스 레슨. 40개 중 17번째.
게임 오버 후에도 플레이어가 프로그램을 다시 시작할 필요가 없어야 합니다. R 키로 새 게임을 시작하도록 하세요. 바뀐 값을 모두 처음 상태로 되돌리세요.
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)조건이 중요합니다. (lives == 0 or score == 10)가 없으면 게임 도중에 R 키를 눌렀을 때 점수가 초기화됩니다. 괄호는 두 종료 조건을 묶으므로 and가 두 조건 모두에 적용됩니다.
플레이어에게 키를 알려 주세요. 결과 아래에 Press R to play again을 표시하세요.
챌린지
중급- KEYDOWN 분기에서 키가
pygame.K_r이고 게임이 종료되었을 때 점수를 0으로, 목숨을 3으로,basket.x를 200으로 설정하고, 임의의 x 위치에서y = -20부터 새 블록을 떨어뜨립니다. - 게임이 종료되었을 때
Press R to play again도(240, 200)을 중심으로 표시합니다.
직접 해보기
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
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 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 플레이그라운드