Menu
CoddyTech

箱子藏住了宝石

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

箱子先于宝石绘制,所以宝石会显示在箱子上方。要让宝石能藏在箱子下面,就要在宝石之后绘制箱子:最后绘制的内容会遮住已经绘制的内容。

这样,按下箱子时就不会触发宝石的检测,让玩家捡到看不见的宝石。两个 if 检测都会运行。使用 elif 时,只有第一个条件为假,才会运行第二个条件,因此只有其中一个条件会响应按下操作:

if crate.collidepoint(event.pos):
    dragging = True
elif gem.collidepoint(event.pos):
    print("Got it!")

先检测绘制在最上层的内容。这样,按下箱子时就不会触发它后面的宝石。

较深的边缘会让盒子看起来更结实。用较深的颜色和指定的宽度再次绘制同一个 Rect,这样只会在填充色上绘制它的轮廓。

challenge icon

挑战

简单

让 crate 遮住 gem,并避免按下它时误触 gem。

  1. 把 crate 的绘制语句移到 gem 的轮廓之后,并在它下面再次绘制 crate,颜色为 (110, 70, 35),宽度为 3,作为它的边框。
  2. 在 MOUSEBUTTONDOWN 分支中,把 gem 对应的 if 改成 elif,放在 crate 的检查之后。

按“开始”,把 crate 拖到 gem 上,再点击它:gem 会保持隐藏,也不会出现粉色标记。然后按“检查”。

亲手试试

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)
crate = pygame.Rect(40, 230, 60, 60)
dragging = False
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 crate.collidepoint(event.pos):
                dragging = True
            if gem.collidepoint(event.pos):
                score += 1
                gem.x = random.randint(15, 435)
                gem.y = random.randint(55, 315)
        elif event.type == pygame.MOUSEBUTTONUP:
            dragging = False
        elif event.type == pygame.MOUSEMOTION and dragging:
            crate.move_ip(event.rel)

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (150, 100, 50), crate)
    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 在线编辑器