【问题标题】:Stopping python from running certain sections of code if an object is deleted如果删除对象,则停止 python 运行某些代码部分
【发布时间】:2020-10-11 17:45:22
【问题描述】:

当玩家输入字母“w”时,玩家的 z 值增加 1,敌人的 x 值增加 0.5。我希望在玩家输入字母“e”时删除敌人对象,并在正常按下 w 时增加 z 值。如果删除对象,如何让 python 忽略某些代码部分?

class Enemy:
    x = 1


play = True
z = 1
while play:
    command = input('')
    if command == 'e':
        del Enemy
    if command == 'w':
        z += 1
        print(z)
    if z >= Enemy.x:
        # stop this from being executed after e is pressed
        Enemy.x += 0.5
        print(Enemy.x)

【问题讨论】:

  • 您不能在 Python 中手动删除对象(del thing 只是取消绑定一个变量),并且您不应该尝试将删除对象用作任何事情的触发器或条件。

标签: python object del


【解决方案1】:

你可以像这样使用布尔值:

class Enemy:
    x = 1

play = True
z = 1
deleted = False
while play:
    command = input('')
    if command == 'e':
        del Enemy
        deleted = True
    if command == 'w':
        z += 1
        print(z)
    if z >= Enemy.x and not deleted:
        Enemy.x += 0.5
        print(Enemy.x)

【讨论】:

    【解决方案2】:

    您不应该尝试删除课程。相反,您可以创建一个存储游戏状态的游戏上下文。这将包含一个敌人对象(如果敌人被删除,则可以是None)和与特定游戏相关的其他变量。然后开始游戏,创建一个新的 Game 实例并传递一个新的 Enemy 实例。这将使您能够以更易于维护的方式发展您的游戏:

    class Enemy:
        x = 1
    
    class Game:
        def __init__(self, enemy):
            self.enemy = enemy
            self.play = True
            self.z = 1
    
    game = Game(Enemy()) # new game with fresh state (enemy, z, etc)
    
    while game.play:
        command = input('')
        if command == 'e':
            game.enemy = None
        if command == 'w':
            game.z += 1
            print(game.z)
        if game.enemy is not None  and game.z >= game.enemy.x:
            # stop this from being executed after e is pressed
            game.enemy.x += 0.5
            print(game.enemy.x)
    

    您可以通过在 Game 类的循环方法中创建内容来改进上述内容。并且,不是直接操作game.enemy.x,而是给enemy 类一个增加分数的方法。这将允许不同的敌人有不同的行为,等等......

    【讨论】:

    • 关于删除的主题,我认为 Enemy 实例应该有一个 __del__ 方法来打印一些适当的戏剧性内容:)
    最近更新 更多