【问题标题】:Variable in for loop could not incrementfor 循环中的变量不能递增
【发布时间】:2020-01-18 10:46:12
【问题描述】:

这是一个关于射击游戏的项目的一部分。变量fail_times 没有像预期的那样增加。我应该如何处理这个问题?

def check_fail(bullets,stats,screen,fail_times):   
        for bullet in bullets:  
            if bullet.rect.right>=screen.get_rect().right:  
                bullets.remove(bullet)    
                fail_times+=1    
                print(fail_times)    
            elif fail_times>3:
                stats.game_active=False   
                pygame.mouse.set_visible(True)    

【问题讨论】:

  • 你的意思是:它不会从函数外部增加。这是预期的。因为整数是不可变的。返回值,并将其分配回去。或者使用类。
  • 在迭代时不要修改它。特别是您在for bullet in bullets 中有bullets.remove(bullet)。这会导致你的循环行为怪异。
  • 我还怀疑您不想使用 elif - 无论以前的条件如何,您可能都想在 fail_times>3 时运行该主体。
  • @Jean-FrançoisFabre:不,我不是那个意思。你注意到'print(fail_times)' 代码了吗? fail_times 不会在函数内部递增。
  • @AlexHall 如果我使用for bullet in bullets.copy(),会更好吗?

标签: python macos variables pygame


【解决方案1】:

如果您使用类变量创建一个类,它将具有您正在寻找的范围:

class game:
    def __init__(self, fail_times=0):
        self.fail_times = fail_times

    def check_fail(self, bullets, stats, screen):
        for bullet in bullets:
            if bullet.rect.right >= screen.get_rect().right:
                bullets.remove(bullet)
                self.fail_times += 1
                print(fail_times)
            elif fail_times > 3:
                stats.game_active = False
                pygame.mouse.set_visible(True)

然后要使用它,您必须实例化该类:

my_game = game()
my_game.check_fail(bullets, stats, screen)

【讨论】:

  • 非常感谢。这就是我想要的!
  • 很高兴听到这个消息!如果它解决了您的问题,请不要忘记接受答案;)
猜你喜欢
  • 1970-01-01
  • 2011-10-15
  • 2020-02-10
  • 2020-01-21
  • 2017-03-22
  • 2017-01-26
  • 2014-09-10
  • 2020-06-11
  • 1970-01-01
相关资源
最近更新 更多