Menu
CoddyTech

一个球类

Coddy 用 Pygame 制作游戏 课程的第 38 课,共 41 课。

这个球包含一个 Rect、两个数字以及它要做的事:移动、反弹和绘制。像处理精灵那样,把它做成一个类:类会把数据和使用这些数据的函数放在一起。

class Ball:
    def __init__(self):
        self.rect = pygame.Rect(293, 193, 14, 14)
        self.vx = 5
        self.vy = 4

    def move(self):
        self.rect.x += self.vx
        self.rect.y += self.vy

ball = Ball()会创建一个球对象并运行 __init__。在类中,self表示这个对象,所以 self.vx就是这个球自己的 vx。类中的函数叫作方法:ball.move()会调用一个方法。

在类外,球的 Rect 现在是 ball.rect,速度则是 ball.vx和 ball.vy,所以挡板和计分代码会从这里读取它们。游戏的运行效果和之前一样。

challenge icon

挑战

困难

把球写成一个会移动并绘制自身的类。

  1. 在顶部写出 class Ball,包含 __init__(self.rect、self.vx = 5、self.vy = 4)、move()(移动,并在碰到顶部和底部时反弹)以及 draw(surface)。
  2. 创建 ball = Ball(),并在循环中调用 ball.move() 和 ball.draw(screen)。
  3. 在其他所有地方,写成 ball.rect、ball.vx 和 ball.vy。

按“开始”:游戏的运行效果和之前完全一样。然后按“检查”。

亲手试试

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
winner = None

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:
            if winner is None:
                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
        if left_score == 5:
            winner = "Left player wins!"
        elif right_score == 5:
            winner = "Right player wins!"

    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 winner is not None:
        message = font.render(winner, True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(300, 120)))
    elif 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 制作游戏中的所有课

自己练习: Pygame 在线编辑器