Menu
CoddyTech

箱子下面的宝石

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

现在,箱子就是游戏的核心。每颗宝石都会出现在箱子下面:把箱子拖开并点击宝石,箱子就会移到下一颗宝石上。

Rect 有一个 center,也就是它正中间的点。把一个 Rect 的中心设为另一个 Rect 的中心,它们就会正好重叠,无论它们的大小如何:

gem = pygame.Rect(300, 120, 30, 30)
crate = pygame.Rect(0, 0, 60, 60)
crate.center = gem.center

只有 crate 会移动到 (285, 105, 60, 60)。在循环开始前为第一颗宝石执行一次,每次宝石换到新位置时再执行一次。

challenge icon

挑战

简单

把每颗宝石都藏在箱子下面。

  1. 创建 crate 后,立即设置 crate.center = gem.center。
  2. 在宝石分支中,设置新的 gem.y 后,再次设置 crate.center = gem.center。

按“开始”,把箱子拖开并点击宝石:箱子会跳到下一颗宝石上。然后按“检查”。

亲手试试

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
            elif 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))
    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)
    pygame.draw.rect(screen, (150, 100, 50), crate)
    pygame.draw.rect(screen, (110, 70, 35), crate, 3)
    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 在线编辑器