猿问

得分不更新 Pong Pygame

我不确定为什么分数没有更新。当任一玩家得分时,调试器打印 0。这是我的分数变量。


player_score = 0

opponent_score = 0

basic_font = pygame.font.Font('freesansbold.ttf', 32)


And the variables for rendering the score:


player_text = basic_font.render(f'{player_score}', False, light_grey)

screen.blit(player_text, (660, 470))


opponent_text = basic_font.render(f'{opponent_score}', False, light_grey)

screen.blit(opponent_text, (600, 470))

还有我的更新方法。


    def update(self, left_paddle, right_paddle, player_score, opponent_score):

    self.rect.x += self.vx

    self.rect.y += self.vy


    if self.rect.top <= 0 or self.rect.bottom >= screen_height:

        self.vy *= -1


    if self.rect.left <= 0:

        self.ball_start()

        player_score += 1


    if self.rect.right >= screen_width:

        self.ball_start()

        opponent_score += 1


    if self.rect.colliderect(left_paddle) or self.rect.colliderect(right_paddle):

        self.vx *= -1


def ball_start(self):

    self.rect.center = (screen_width / 2, screen_height / 2)

    self.vy *= random.choice((1, -1))

    self.vx *= random.choice((1, -1))

然后我调用更新方法:


ball.update(left_paddle, right_paddle, player_score, opponent_score)


这是项目的代码。非常感谢您的帮助。


子衿沉夜
浏览 64回答 1
1回答

至尊宝的传说

您的更新没有反映在全局变量中,因为您根本没有更新它们。您正在更新它们的本地副本,这是通过将它们传递给Ball.update函数而获得的。试试这个:def update(self, left_paddle, right_paddle):&nbsp; &nbsp; global player_score, opponent_score&nbsp; &nbsp; ...&nbsp; &nbsp; if self.rect.left <= 0:&nbsp; &nbsp; &nbsp; &nbsp; self.ball_start()&nbsp; &nbsp; &nbsp; &nbsp; player_score += 1&nbsp; &nbsp; if self.rect.right >= screen_width:&nbsp; &nbsp; &nbsp; &nbsp; self.ball_start()&nbsp; &nbsp; &nbsp; &nbsp; opponent_score += 1&nbsp; &nbsp; ...&nbsp; &nbsp; # function ends here我认为最好的办法是创建一个Player类并只在那里跟踪分数,然后将此类的实例传递Player给update函数。然后,稍后从这些实例中检索分数。
随时随地看视频慕课网APP

相关分类

Python
我要回答