点击宝石
本课属于 Coddy Pygame 学习旅程的“游戏循环”单元。第 14 课,共 35 课。
get_pos 表示指针的位置。点击是一种事件:鼠标按键按下时,事件循环会在该帧收到一个 pygame.MOUSEBUTTONDOWN 事件。它的 event.pos 是点击发生的位置。
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
if gx <= x <= gx + 30 and gy <= y <= gy + 30:
print("Got it!")宝石位于一个边长为 30 的正方形内,正方形的起点是 (gx, gy)。当 x 在正方形的左边和右边之间,并且 y 在上边和下边之间时,点击就落在宝石上。Python 允许你用 gx <= x <= gx + 30 表示“x 的范围是从 gx 到 gx + 30”。
random.randint(a, b) 会从 a 到 b 选取一个整数,因此被抓到的宝石可以跳到新的位置。
挑战
简单点击宝石时,让它跳开。
- 在顶部添加
import random。 - 在事件循环中,响应
MOUSEBUTTONDOWN时,如果event.pos位于从(gx, gy)到(gx + 30, gy + 30)的正方形内,就设置gx = random.randint(15, 435)和gy = random.randint(55, 315)。
按“开始”并点击宝石:它会跳到新的位置。然后点击“检查”。
亲手试试
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Gem Hunt")
clock = pygame.time.Clock()
gx, gy = 225, 165
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((30, 30, 46))
gem_points = [(gx + 15, gy), (gx + 30, gy + 15), (gx + 15, gy + 30), (gx, gy + 15)]
pygame.draw.polygon(screen, (80, 220, 255), gem_points)
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 在线编辑器