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

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值