寻找宝石
本课属于 Coddy Pygame 学习旅程的“游戏循环”单元。第 20 课,共 35 课。
一局 Gem Hunt 持续 30 秒。用帧数计算时间:每秒 60 帧,10 秒就是 600 帧。
time_left = 600
while running:
# 事件
if time_left > 0:
time_left -= 1当 time_left 达到 0 时,游戏会停止响应点击和拖动,分数行会显示结果:在某个事件的测试中添加 and time_left > 0。
顶部的进度条会显示剩余时间。它的宽度表示本局剩余时间所占的比例:在 600 帧的一局中,进度条最大宽度为 200 像素,200 * time_left // 600 在开始时的值是 200,中途是 100,结束时是 0。
挑战
中等每轮设置为 30 秒。
- 在循环之前,设置
time_left = 1800。处理完事件后,如果它大于 0,就将它减 1。 - 在
MOUSEBUTTONDOWN和MOUSEMOTION检查中添加and time_left > 0。 - 在分数行之后,绘制一个绿色矩形,颜色为
(120, 200, 120),位置和尺寸为(0, 0, 480 * time_left // 1800, 6)。
按“开始”:绿色条会逐渐缩短,30 秒后点击将不起作用。然后按“检查”。
亲手试试
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)
crate.center = gem.center
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)
crate.center = gem.center
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 在线编辑器