상자 끌기
Coddy Pygame 여정의 게임 루프 섹션에 포함된 레슨. 35개 중 17번째.
드래그에는 세 가지 이벤트가 있습니다. 상자에서 버튼을 누르고(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)은 같은 만큼 상자를 움직이므로, 잡은 지점이 포인터 아래에 계속 놓여 있게 됩니다.
챌린지
중급플레이어가 상자를 끌 수 있게 하세요.
- 반복문 전에
crate = pygame.Rect(40, 230, 60, 60)와dragging = False를 만드세요. MOUSEBUTTONDOWN일 때crate.collidepoint(event.pos)가 참이면dragging = True로 설정하세요.MOUSEBUTTONUP일 때는False로 설정하세요.- 드래그하는 동안
MOUSEMOTION이 발생하면crate.move_ip(event.rel)을 호출하세요. - 보석을 그리기 전에 갈색
(150, 100, 50)으로crate를 그리세요.
‘플레이’를 누르고 상자를 끌어 보세요. 상자가 포인터를 따라옵니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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 플레이그라운드