我不確定為什么分數沒有更新。當任一玩家得分時,調試器打印 0。這是我的分數變量。player_score = 0opponent_score = 0basic_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 *= -1def 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)這是項目的代碼。非常感謝您的幫助。
1 回答

至尊寶的傳說
TA貢獻1789條經驗 獲得超10個贊
您的更新沒有反映在全局變量中,因為您根本沒有更新它們。您正在更新它們的本地副本,這是通過將它們傳遞給Ball.update函數而獲得的。
試試這個:
def update(self, left_paddle, right_paddle):
global player_score, opponent_score
...
if self.rect.left <= 0:
self.ball_start()
player_score += 1
if self.rect.right >= screen_width:
self.ball_start()
opponent_score += 1
...
# function ends here
我認為最好的辦法是創建一個Player類并只在那里跟蹤分數,然后將此類的實例傳遞Player給update函數。然后,稍后從這些實例中檢索分數。
添加回答
舉報
0/150
提交
取消