Menu
CoddyTech

满天繁星

本课属于 Coddy Pygame 学习旅程的“游戏窗口中的 Python”单元。第 33 课,共 33 课。

天空中有 20 颗星星时,游戏就结束了。两件事会发生变化:点击不再添加星星,并且会显示一条消息。两处都会读取同一个列表:

if event.type == pygame.MOUSEBUTTONDOWN and len(stars) < 20:
    stars.append(event.pos)
if len(stars) == 20:
    message = font.render("The sky is full!", True, (230, 230, 240))
    screen.blit(message, message.get_rect(center=(320, 240)))

message.get_rect(center=(320, 240)) 是文字图像的矩形,文字图像的中心位于 (320, 240)。在这个位置进行绘制后,无论文字有多长,它都会显示在窗口中央。

这里要检查 == 20,而不是 > 20:上限会让列表最多只有 20 个元素,因此它不会包含更多元素。

天空满了之后,你能做的就只剩下欣赏它了。第 2 单元会介绍如何按键重新开始游戏,以及如何以胜利或失败结束游戏。

challenge icon

挑战

中等

完成“夜空”挑战:天空中有 20 颗星星。

  1. 只有在 len(stars) < 20 时,点击才添加一颗星星。
  2. 当 len(stars) == 20 时,在 (320, 240) 处居中显示 The sky is full!,颜色为 (230, 230, 240)。

点击“开始”,再点击 20 次:会显示 The sky is full!。然后点击“检查”。

亲手试试

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Night Sky")
clock = pygame.time.Clock()

# 在游戏循环开始前,先在这里做好准备。
stars = []
font = pygame.font.Font(None, 36)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            stars.append(event.pos)

    # 每一帧在这里更新内容。

    screen.fill((20, 24, 48))
    # 填充屏幕后,在这里绘制。
    pygame.draw.circle(screen, (240, 230, 160), (560, 80), 40)
    pygame.draw.rect(screen, (14, 16, 30), (0, 430, 640, 50))
    for star in stars:
        colour = (255, 255, 255)
        if random.randint(1, 30) == 1:
            colour = (110, 120, 170)
        pygame.draw.circle(screen, colour, star, 3)
    text = font.render(f"Stars: {len(stars)}/20", True, (230, 230, 240))
    screen.blit(text, (20, 20))

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

游戏窗口中的 Python中的所有课

自己练习: Pygame 在线编辑器