Menu
CoddyTech

悬停高亮

本课属于 Coddy Pygame 学习旅程的“游戏循环”单元。第 16 课,共 35 课。

每次都检查 gx <= x <= gx + 30 会很麻烦。Pygame 有一个用于矩形的类 pygame.Rect,它能把位置和尺寸放在一起,并替你进行这些检查:

gem = pygame.Rect(100, 40, 30, 30)

if gem.collidepoint(event.pos):
    print("Got it!")

当点位于 Rect 内部时,gem.collidepoint(point) 的结果是 True。你仍然可以读取和更改 gem.x 和 gem.y。Rect 还为自身的点提供了名称:midtop、midright、midbottom 和 midleft 分别表示各条边的中点;对于 gem 来说,它们就是四个角。

用指针的位置进行同样的检查,就能知道玩家是否将指针指向了 gem。游戏会用高亮来显示这一点:

if gem.collidepoint(pygame.mouse.get_pos()):
    pygame.draw.rect(screen, (255, 255, 255), gem.inflate(6, 6), 1)

gem.inflate(6, 6) 会创建一个新的 Rect,它的宽度和高度各增加 6 像素,中心位置不变,因此这个轮廓会位于 gem 外侧 3 像素处。

challenge icon

挑战

简单

给宝石设置一个 Rect,并在鼠标指针位于其上时为它描边。

  1. 将 gx, gy = 225, 165 替换为 gem = pygame.Rect(225, 165, 30, 30),并在之前使用 gx 和 gy 的地方改用 gem.x 和 gem.y。
  2. 使用 gem.collidepoint(event.pos) 检测点击。
  3. 绘制宝石后,当 gem.collidepoint(pygame.mouse.get_pos()) 为真时,为 gem.inflate(10, 10) 绘制黄色 (255, 196, 0) 描边,宽度为 2 像素。

按“开始”,然后将鼠标指向宝石:你会看到黄色描边。然后点击“检查”。

亲手试试

import random
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
score = 0

running = True
while running:
    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:
                score += 1
                gx = random.randint(15, 435)
                gy = random.randint(55, 315)

    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)
    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 在线编辑器