상자가 보석을 가려요
Coddy Pygame 여정의 게임 루프 섹션에 포함된 레슨. 35개 중 18번째.
상자는 보석보다 먼저 그려지므로 보석은 상자 위에 표시됩니다. 보석이 아래에 가려질 수 있는 상자라면 보석을 그린 뒤 상자를 그리세요. 마지막에 그린 것이 이미 그려진 것을 덮습니다.
그러면 상자를 누른 입력이 보석의 판정에 도달해 플레이어가 볼 수 없는 보석을 획득하는 일이 없어야 합니다. 두 개의 if 판정은 모두 실행됩니다. elif를 사용하면 첫 번째 판정이 거짓일 때만 두 번째 판정이 실행되므로, 둘 중 하나만 누름 입력을 처리합니다.
if crate.collidepoint(event.pos):
dragging = True
elif gem.collidepoint(event.pos):
print("Got it!")위에 그려진 것을 먼저 판정하세요. 그러면 상자를 누른 입력은 뒤에 있는 보석까지 도달하지 않습니다.
더 어두운 테두리를 그리면 상자가 단단해 보입니다. 같은 Rect를 더 어두운 색과 너비를 지정해 다시 그리면 채워진 부분 위에 윤곽선만 그려집니다.
챌린지
쉬움상자로 보석을 가리고, 상자를 눌러도 보석을 잡지 않게 하세요.
- 상자를 그리는 줄을 보석의 윤곽선을 그린 뒤로 옮기고, 그 아래에서 상자의 테두리로
crate를(110, 70, 35)색상과 너비3으로 다시 그리세요. MOUSEBUTTONDOWN분기에서 보석의if를 상자 검사 아래에 있는elif로 바꾸세요.
‘플레이’를 누르고, 상자를 보석 위로 끌어다 놓은 다음 클릭하세요. 보석은 계속 가려져 있고 분홍색 표시도 나타나지 않습니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Gem Hunt")
clock = pygame.time.Clock()
gem = pygame.Rect(225, 165, 30, 30)
crate = pygame.Rect(40, 230, 60, 60)
dragging = False
score = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if crate.collidepoint(event.pos):
dragging = True
if gem.collidepoint(event.pos):
score += 1
gem.x = random.randint(15, 435)
gem.y = random.randint(55, 315)
elif event.type == pygame.MOUSEBUTTONUP:
dragging = False
elif event.type == pygame.MOUSEMOTION and dragging:
crate.move_ip(event.rel)
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (150, 100, 50), crate)
gem_points = [gem.midtop, gem.midright, gem.midbottom, gem.midleft]
pygame.draw.polygon(screen, (80, 220, 255), gem_points)
if gem.collidepoint(pygame.mouse.get_pos()):
pygame.draw.rect(screen, (255, 196, 0), gem.inflate(10, 10), 2)
for i in range(score):
pygame.draw.rect(screen, (240, 110, 180), (10 + 10 * i, 14, 8, 8))
mouse_x, mouse_y = pygame.mouse.get_pos()
pygame.draw.circle(screen, (240, 240, 240), (mouse_x, mouse_y), 10, 2)
pygame.display.flip()
clock.tick(60)
pygame.quit()
게임 루프의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드