乒乓球游戏中的移动球 - Pygame

Moving ball in Pong Game - Pygame

我是 Pygame 的新手,我刚开始开发 Pong 游戏。下面的代码还没有写完,但是不知道为什么,球不会动了。仅当我在“draw_ball”方法中设置“ball_draw = pygame...”而不是初始化方法时,它才有效。但是,如果我这样做,我就不能在 class 中使用“wallCollision”方法,因为“ball_draw”将是局部变量而不是整个 class 的属性因此,无法通过其他方法访问。我怎样才能解决这个问题?感谢您的帮助。

import pygame, sys
pygame.init()
clock = pygame.time.Clock()

screen_width = 1280
screen_height = 960
bgColor = pygame.Color("grey12")
lightGrey = (200, 200, 200)

screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Pong Game")

class BALL:
    def __init__(self):
        self.ball_width = 30
        self.ball_height = 30
        self.ball_x = screen_width/2 - self.ball_width
        self.ball_y = screen_height/2 - self.ball_height
        self.ball_speed_x = 7
        self.ball_speed_y = 7
        self.ball_draw = pygame.Rect(self.ball_x, self.ball_y, self.ball_width, self.ball_height)
    def draw_ball(self):
        pygame.draw.ellipse(screen, lightGrey, self.ball_draw)
    def move_ball(self):
        self.ball_x += self.ball_speed_x
        self.ball_y += self.ball_speed_y
    def wallCollision(self):
        if self.ball_draw.bottom >= screen_height:
            self.ball_speed_y *= -1
        if self.ball_draw.top <= 0:
            self.ball_speed_y *= -1
        if self.ball_draw.left <= 0:
            self.ball_speed_x *= -1
        if self.ball_draw.right >= screen_width:
            self.ball_speed_x *= -1

class PLAYER1:
    def __init__(self):
        self.player1_width = 10
        self.player1_height = 140
        self.player1_x = screen_width - 20
        self.player1_y = screen_height/2 - 70
    def draw_player1(self):
        player1_draw = pygame.Rect(self.player1_x, self.player1_y, self.player1_width, self.player1_height)
        pygame.draw.rect(screen, lightGrey, player1_draw)
    def move_player1(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_UP] and self.player1_y >= 0:
            self.player1_y -= 5
        if keys[pygame.K_DOWN] and self.player1_y <= screen_height:
            self.player1_y += 5

ball = BALL()
player1 = PLAYER1()

while True:

    # Checking for events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    # Drawing on screen
    screen.fill(bgColor)
    ball.draw_ball()
    player1.draw_player1()

    # Movement and Collisions
    ball.move_ball()
    player1.move_player1()
    ball.wallCollision()

    # Updating screen
    pygame.display.flip()
    # Defining 60 frames per second (FPS)
    clock.tick(60)

您使用矩形属性 self.ball_draw 绘制球。因此,如果您移动球并更改 self.ball_xself.ball_y 属性,则需要更新矩形:

class BALL:
    # [...]

    def draw_ball(self):
        pygame.draw.ellipse(screen, lightGrey, self.ball_draw)

    def move_ball(self):
        self.ball_x += self.ball_speed_x
        self.ball_y += self.ball_speed_y
        self.ball_draw.topleft = (self.ball_x, self.ball_y)