Hunt the Wumpus第二个版本---多怪兽,多洞穴,洞穴间双向互通

其中,将洞穴连起来的算法要好好体会。

学习构建临时变量列表,确认循环用FOR,非确定循环用 WHILE,并定好退出条件。

from random import choice

cave_numbers = range(0,20)
caves = []
for i in cave_numbers:
    caves.append([])
#保证所有洞穴双向连通
unvisited_caves = range(0,20)
visited_caves = [0]
unvisited_caves.remove(0)

while unvisited_caves != []:
    i = choice(visited_caves)
    if len(caves[i]) >= 3:
        continue

    next_cave = choice(unvisited_caves)
    caves[i].append(next_cave)
    caves[next_cave].append(i)

    visited_caves.append(next_cave)
    unvisited_caves.remove(next_cave)

    '''
    for number in cave_numbers:
        print number, ":", caves[number]
        print "-------visited cave------"
    '''
print caves
#保证每个洞穴与另外三个洞穴相连
for i in cave_numbers:
    while len(caves[i]) < 3:
        passage_to = choice(cave_numbers)
        caves[i].append(passage_to)

    '''
    for number in cave_numbers:
              print number, ":", caves[number]
    print "-------other cave----------"
    '''
print caves
#加入怪兽的朋友
wumpus_location = choice(cave_numbers)
wumpus_friend_location = choice(cave_numbers)
player_location = choice(cave_numbers)
while player_location == wumpus_location or player_location == wumpus_friend_location:
    player_location = choice(cave_numbers)

print "Welcome to Hunt the Wumpus!"
print "You can see ", len(cave_numbers), "caves"
print "To play, just type the number"
print "of the cave you wish to enter next"

while True:
    print "You are in cave ", player_location
    print "From here, you can see caves:", caves[player_location]
    if wumpus_location in caves[player_location] :
        print "I smell a wumpus!"
    if wumpus_friend_location in caves[player_location]:
        print "I smell an even stinkier wumpus!"
    '''
    if (player_location == wumpus_location - 1 or
        player_location == wumpus_location + 1):
        print "I smell a wumpus!"
    if (player_location == wumpus_friend_location - 1 or
        player_location == wumpus_friend_location + 1):
        print "I smell an even stinkier wumpus!"
    '''
    print "Which cave next?"
    player_input = raw_input(">")
    if (not player_input.isdigit() or
        int(player_input) not in caves[player_location]):
        print player_input + "?"
        print "That's not a direction that I can see!"
        continue
    else:
        player_location = int(player_input)
        if player_location == wumpus_location:
            print "Aargh! you got eaten by a wumpus!"
            break
        if player_location == wumpus_friend_location:
            print "Aargh! you got eaten by a wumpus's friend!"
            break

Hunt the Wumpus第二个版本---多怪兽,多洞穴,洞穴间双向互通

上一篇:51nod-1670-打怪兽(递推/组合数学)


下一篇:错误信息:内存位置访问无效。 (Exception from HRESULT: 0x800703E6)