我有一个怪物在房间之间随机移动的代码,但全局值出现了意外的意图错误。
def monster(): """moves the monster randomly"""
global monster_current_room
if monster_current_room["name"] != current_room:
print('The monster is currently in', monster_current_room["name"])
exits = list(monster_current_room["exits"].values())
if random.randint(1, 4) == 4:
monster_current_room = rooms[random.choice(exits)]
elif monster_current_room["name"] == current_room:
game_over = True
如果我取消了全局值,它就充当了定义的末尾,并且希望在定义和全局值之间有两条线。当我尝试使用缩进运行时,程序失败并出现错误。
您放错了函数注释:
def monster():
"""
moves the monster randomly
"""
global monster_current_room
if monster_current_room["name"] != current_room:
print('The monster is currently in', monster_current_room["name"])
exits = list(monster_current_room["exits"].values())
if random.randint(1, 4) == 4:
monster_current_room = rooms[random.choice(exits)]
elif monster_current_room["name"] == current_room:
game_over = True
或者,如果你喜欢内联评论,你可以像一样
def monster(): # moves the monster randomly
global monster_current_room
if monster_current_room["name"] != current_room:
print('The monster is currently in', monster_current_room["name"])
exits = list(monster_current_room["exits"].values())
if random.randint(1, 4) == 4:
monster_current_room = rooms[random.choice(exits)]
elif monster_current_room["name"] == current_room:
game_over = True
当您编写像这样的多行字符串时
"""
moves the monster randomly
"""
它必须遵守python代码中经典语句的规则。所以你不能把它们放在任何你想点赞的地方。