新手python问题求解

错误提示:Traceback (most recent call last):
File "G:\py编程\2.py", line 7, in <module>
visit_cave(0)
NameError: name 'visit_cave' is not defined

相关函数不是定义了吗,怎么还会这样,求解,谢谢

代码如下
from random import choice
cave_numbers=range(0,20)
unvisited_caves=range(0,20)
visited_caves=[]
'caves=setup_caves(cave_numbers)'

visit_cave(0)
print_caves()
link_caves()
print_caves()
finish_caves()

wumpus_location=choice(cave_numbers)
player_location=choice(cave_numbers)
while player_location==wumpus_location:
player_location=choice(cave_numbers)

while True:
print_location(player_location)
new_location=get_next_location()
if new_location is not None:
player_location=new_location
if player_location==wumpus_location:
print"你被怪物吃掉了"
break

def create_tunnel(cave_from,cave_to):
"""在出入洞穴中创建通道"""
caves [cave_from].append(cave_to)
caves [cave_to].append(cave_from)

def visit_cave(cave_number):
"""标记进入的洞穴"""
visited_cave.append(cave_number)
unvisited_caves.remove(cave_number)

def choose_cave(cave_list):
"""把洞穴放到列表中,确保每个洞穴至少连通三个洞穴"""
cave_number=choice(cave_list)
while len(caves[cave_number])>=3:
cave_number=choice(cave_list)
return cave_number

def print_caves():
"""打印洞穴网络"""
for number in cave_numbers:
print number,":",caves[number]
print '-----------------'

def setup_caves(cave_numbers):
"""创建洞穴列表"""
caves=[]
for cave in cave_numbers:
cave.append([])
return caves

def link_caves():
"""确保所以洞穴都有两条通道"""
while unvisited_caves!=[]:
this_cave=choose_cave(visited_caves)
next_cave=choose_cave(unvisited_caves)
create_tunnel(this_cave,next_cave)
visit_cave(next_cave)

def finished_caves():
"""确保每个洞穴都有3条通道"""
for cave in cave_numbers:
while le(caves[cave])<3:
passage_to=choose_cave(cave_numbers)
caves[cave].append(passage_to)

def print_location(player_location):
"""告诉玩家你在哪里"""
print "你所在洞穴",player_location
print "你在这里,可以看到洞穴:"
print caves[player_location]
if wumpus_location in caves[player_location]:
print "我问到怪兽的气味"

def get_Next_location():
"""到下个洞穴"""
print "去哪个洞穴"
player_input=raw_input(">")
if(not player_input.isdigit()or int(player_input)not in caves[player_location]):
print player_input+"?"
print "这里什么都没有"
return None
else:
return int(player_input)

这段代码问题太多了。不妨从这里开始:

    不要一次编写超过20行代码,老代码能运行了,再加新代码

    使用pylint等工具检查代码

    避免使用全局变量


NameError: name 'visit_cave' is not defined
这个错误是因为在第7行调用这个函数的时候,这个函数还没有定义。方法是把代码按下面的顺序重新排序:

    import语句

    变量定义和初始化

    函数定义

    具体语句(模块初始化)

温馨提示:答案为网友推荐,仅供参考
第1个回答  2016-08-04
你把def visit_cave(cave_number):那一堆放到上面去试试
相似回答