Menu
CoddyTech

상자 끌기

Coddy Pygame 여정의 게임 루프 섹션에 포함된 레슨. 32개 중 16번째.

드래그에는 세 가지 이벤트가 필요합니다. 상자를 누르고(MOUSEBUTTONDOWN), 포인터를 움직이고(MOUSEMOTION, 여러 번), 버튼에서 손을 뗍니다(MOUSEBUTTONUP). 변수 하나로 그 사이에 드래그가 진행 중인지 기억합니다.

elif event.type == pygame.MOUSEBUTTONDOWN:
    if crate.collidepoint(event.pos):
        dragging = True
elif event.type == pygame.MOUSEBUTTONUP:
    dragging = False
elif event.type == pygame.MOUSEMOTION and dragging:
    crate.move_ip(event.rel)

MOUSEMOTION 이벤트의 event.rel은 (x, y) 형식으로, 포인터가 직전 이벤트 이후 얼마나 움직였는지를 나타냅니다. crate.move_ip(event.rel)은 같은 거리만큼 상자를 움직이므로, 잡은 지점이 포인터 아래에 계속 놓여 있습니다.

상자는 보석 다음에 그려지므로 보석을 가릴 수 있습니다. 따라서 상자를 누를 때 그 아래의 보석이 수집되면 안 됩니다. 먼저 상자를 확인하고, elif로 보석을 확인하여 둘 중 하나만 누름 이벤트를 처리하도록 합니다.

challenge icon

챌린지

중급
  1. 반복문 전에 crate = pygame.Rect(40, 230, 60, 60)와 dragging = False를 만드세요.
  2. MOUSEBUTTONDOWN 이벤트가 발생하면, 누른 위치가 상자 위일 때 dragging = True로 설정하고, 그렇지 않으면(elif) 이전과 같이 보석을 확인하세요.
  3. MOUSEBUTTONUP 이벤트가 발생하면 dragging = False로 설정하세요. 드래그하는 동안 MOUSEMOTION 이벤트가 발생하면 event.rel만큼 상자를 이동하세요.
  4. 보석의 윤곽선을 그린 다음, 갈색 (150, 100, 50)으로 상자를 그리고, 너비가 3픽셀인 (110, 70, 35) 색 테두리를 추가하세요.

직접 해보기

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)
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 gem.collidepoint(event.pos):
                score += 1
                gem.x = random.randint(15, 435)
                gem.y = random.randint(55, 315)

    screen.fill((30, 30, 46))
    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 플레이그라운드