Menu
CoddyTech

先得 5 分

本课属于 Coddy Pygame 学习旅程的“项目”单元。第 19 课,共 33 课。

第一个得到 5 分的玩家获胜。把获胜者的名字保存在一个初始值为 None 的变量中。None 是 Python 中表示“尚无内容”的值:

winner = None

if left_score == 5:
    winner = "Left player wins!"
elif right_score == 5:
    winner = "Right player wins!"

使用 winner is None 或 winner is not None 来测试。一旦有人获胜,球就会一直等待:只有在 winner is None 时,按空格键才会发球。

在 (300, 120) 处居中显示获胜者,替代发球提示。

challenge icon

挑战

中等

达到 5 分时结束比赛。

  1. 在循环之前,设置 winner = None。得分后,如果 left_score == 5,就将它设置为 "Left player wins!";如果 right_score == 5,就将它设置为 "Right player wins!"。
  2. 只有在 winner is None 时,才能按空格键发球。
  3. 在 (300, 120) 处显示获胜者,而不是显示 Press Space to serve。

按“开始”:达到 5 分时会显示获胜者。然后按“检查”。

亲手试试

import pygame

pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)

ball = pygame.Rect(293, 193, 14, 14)
vx, vy = 5, 4
left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)
left_score = 0
right_score = 0
waiting = False

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            waiting = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        left.y -= 6
    if keys[pygame.K_s]:
        left.y += 6
    if keys[pygame.K_UP]:
        right.y -= 6
    if keys[pygame.K_DOWN]:
        right.y += 6
    left.clamp_ip(screen.get_rect())
    right.clamp_ip(screen.get_rect())

    if not waiting:
        ball.x += vx
        ball.y += vy
        if ball.top <= 0 or ball.bottom >= 400:
            vy = -vy
        if ball.colliderect(left):
            vx = abs(vx)
            vy = (ball.centery - left.centery) // 6
        if ball.colliderect(right):
            vx = -abs(vx)
            vy = (ball.centery - right.centery) // 6
        if ball.left > 600:
            left_score += 1
            ball.center = (300, 200)
            vx = -vx
            waiting = True
        if ball.right < 0:
            right_score += 1
            ball.center = (300, 200)
            vx = -vx
            waiting = True

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), left)
    pygame.draw.rect(screen, (235, 80, 80), right)
    pygame.draw.rect(screen, (255, 196, 0), ball)
    score = font.render(f"{left_score} : {right_score}", True, (240, 240, 240))
    screen.blit(score, score.get_rect(center=(300, 30)))
    if waiting:
        message = font.render("Press Space to serve", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(300, 360)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

项目中的所有课

自己练习: Pygame 在线编辑器