拖动箱子
本课属于 Coddy Pygame 学习旅程的“游戏循环”单元。第 17 课,共 35 课。
拖动需要三个事件。按下箱子上的鼠标按钮(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 在线编辑器