Menu
CoddyTech

回到中间

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

玩家没接到球时,球会从他们这一侧飞出窗口。把球移回中间,再让它朝另一侧飞去。

if ball.right < 0 or ball.left > 600:
    ball.center = (300, 200)
    vx = -vx

ball.right < 0 表示整个球都越过了左边缘,ball.left > 600 表示整个球都越过了右边缘。设置 ball.center 会移动 Rect,使它的中心位于该点;它的大小保持不变。

这里的 vx = -vx 是安全的:球在中间,离任何球拍都很远。

challenge icon

挑战

简单

让错过的球回到中间。

  1. 当整个球越过左边缘或右边缘时,将它的 center 设为 (300, 200)。
  2. 同时反转 vx。

按“开始”,然后让球过去:它会回来并朝另一个方向移动。然后按“检查”。

亲手试试

import pygame

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

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)

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = 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())

    ball.x += vx
    ball.y += vy
    if ball.top <= 0 or ball.bottom >= 400:
        vy = -vy
    if ball.colliderect(left):
        vx = abs(vx)
    if ball.colliderect(right):
        vx = -abs(vx)

    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)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

项目中的所有课

自己练习: Pygame 在线编辑器