【发布时间】: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