首页 > 代码库 > Hunt the Wumpus第二个版本---多怪兽,多洞穴,洞穴间双向互通
Hunt the Wumpus第二个版本---多怪兽,多洞穴,洞穴间双向互通
其中,将洞穴连起来的算法要好好体会。
学习构建临时变量列表,确认循环用FOR,非确定循环用 WHILE,并定好退出条件。
from random import choicecave_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第二个版本---多怪兽,多洞穴,洞穴间双向互通
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。