亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

得分不更新 Pong Pygame

得分不更新 Pong Pygame

子衿沉夜 2022-12-20 15:16:56
我不確定為什么分數沒有更新。當任一玩家得分時,調試器打印 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函數。然后,稍后從這些實例中檢索分數。


查看完整回答
反對 回復 2022-12-20
  • 1 回答
  • 0 關注
  • 77 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號