Почему мяч не движется при вызове обновления (pygame Pong)? - PullRequest
1 голос
/ 29 мая 2020

При вызове ball.update() я ожидал, что мяч должен двигаться, но этого не произошло.

Я думаю, что, возможно, есть проблема с определением bpos как прямоугольного объекта и передачей его в в эллипс, чтобы нарисовать мяч на экране.

игровые прямоугольники

bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)

Причина, по которой я делаю bpos прямоугольным объектом, а затем передаю его для рисования эллипса:

class Ball:
   def __init__(self):
    self.x = screen_width // 2
    self.y = screen_height // 2
    self.speed = 5
    self.vx = self.speed
    self.vy = self.speed


    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, bpos)

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

потому что в конечном итоге, когда дело дойдет до удержания мяча в границах, я хотел бы использовать атрибуты pygame Rect (сверху, снизу, слева, справа) в таком методе обновления, если это возможно.

 def update(self):
            self.x += self.vx
            self.y += self.vy
**if self.top <= 0 or self.bottom >= screen_height:
        self.vy *= -1
    if ball.left <= 0 or self.right >= screen_width:
        self.vx *= -1**

But the ball isnt moving.

In лог игры c видно, что я звоню:

ball.draw (screen) ball.update ()

Был бы очень признателен за ваш вклад. Спасибо. Ниже мой код.

    import pygame, sys


    class Paddle:
        def __init__(self):
            self.rect = pygame.Rect(10, screen_height / 2 - 70, 10, 140)

        def draw(self, screen):
            pygame.draw.rect(screen, light_grey, self.rect)


    class Ball:
        def __init__(self):
            self.x = screen_width // 2
            self.y = screen_height // 2
            self.speed = 5
            self.vx = self.speed
            self.vy = self.speed


        def draw(self, screen):
            pygame.draw.ellipse(screen, light_grey, bpos)

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


    # General setup
    pygame.init()
    clock = pygame.time.Clock()

    # Main Window
    screen_width = 1280
    screen_height = 960

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

    # Colors
    light_grey = (200, 200, 200)
    bg_color = pygame.Color('grey12')

    # Game Rectangles
    ball = Ball()
    bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)
    left_paddle = Paddle()
    right_paddle = Paddle()
    right_paddle.rect.x = screen_width - right_paddle.rect.width

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()

        # Game logic

        screen.fill(bg_color)
        ball.draw(screen)
        left_paddle.draw(screen)
        right_paddle.draw(screen)
        ball.update()

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

1 Ответ

1 голос
/ 29 мая 2020

Проблема не в том, что вы, скажем, используете прямоугольник для bpos. Проблема в том, что вы не обновляете bpos.

Прямоугольник, который вы используете для рисования эллипса, необходимо обновить в вашем Ball.update(). Вы обновляете self.x, y, но не то, что используете для рисования мяча.

Однако используемый прямоугольник должен быть атрибутом экземпляра Ball, а не внешней переменной. Вы должны инициализировать его в init и использовать self.rect.x и self.rect.y для обновления и отслеживания положения мячей. Не сохраняйте позицию одновременно в self.rect.x и self.rect.y и отдельно в self.x, self.y. Это просто приведет к избыточности и возможной несогласованности и ошибке.

Я бы предложил эти изменения.

Измените это:

# Game Rectangles
ball = Ball()
bpos = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)

на что-то вроде этого:

# Game Rectangles
ball = Ball(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30)

и это:

class Ball:
    def __init__(self):
        self.x = screen_width // 2
        self.y = screen_height // 2
        self.speed = 5
        self.vx = self.speed
        self.vy = self.speed


    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, bpos)

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

примерно так:

class Ball:
    def __init__(self, x, y, width, height):
        self.rect = pygame.Rect(x, y, width, height))
        self.speed = 5
        self.vx = self.speed
        self.vy = self.speed


    def draw(self, screen):
        pygame.draw.ellipse(screen, light_grey, self.rect)

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