以下是一个示例代码,展示了如何解决不能连续发射两次火球的问题:
class Player:
def __init__(self):
self.can_cast_fireball = True
def cast_fireball(self):
if self.can_cast_fireball:
print("发射火球")
self.can_cast_fireball = False
else:
print("不能连续发射两次火球")
player = Player()
player.cast_fireball() # 输出:发射火球
player.cast_fireball() # 输出:不能连续发射两次火球
在上面的示例中,我们创建了一个Player
类,并在初始化方法中将can_cast_fireball
属性设置为True
,表示可以发射火球。cast_fireball
方法用于发射火球,如果can_cast_fireball
为True
,则打印"发射火球"并将can_cast_fireball
设置为False
,表示不能连续发射两次火球。如果can_cast_fireball
为False
,则打印"不能连续发射两次火球"。